The <graphics-element> API

This is the API documentation for <graphics-element> source code, which at its code is simply plain JavaScript with a bunch of extra global constants and functions to allow you to quickly but cleanly get (interactive, and animated) graphics onto a page using the native web stack instead of needing some kind of build system.

Note that the index just below is ordered by category, but the full list itself is ordered alphabetically to allow you to search by scrolling as well as searching the index.

Also, if this made a difference in your dev life, consider (temporarily, even?) becoming a patron of my work over on my Patreon page, or send a one-time donation to help keep this project, and others like it, funded. Any amount is appreciated!

constants

disabling functions

dom functions

draw functions

general functions

math functions

matrix functions

projection functions

setter functions

shape functions

transform functions

abs top

Description

Get the absolute value for some input

Examples

function draw() { clear(`white`); translate(0, height / 2); noFill(); setStroke(`black`); line(-huge, 0, huge, 0); const w2 = width / 2; const data = array(width, (x) => [x, x - w2, abs(x - w2)]); setStroke(`red`); plotData(data, 0, 1); setStroke(`blue`); plotData(data, 0, 2); }
function draw() {
  clear(`white`);
  translate(0, height / 2);
  noFill();
  setStroke(`black`);
  line(-huge, 0, huge, 0);

  const w2 = width / 2;
  const data = array(width, (x) => [x, x - w2, abs(x - w2)]);

  setStroke(`red`);
  plotData(data, 0, 1);

  setStroke(`blue`);
  plotData(data, 0, 2);
}

acos top

Description

The inverse cosine function

See also:

acosh top

Description

The hyperbolic inverse cosine function

See https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions#Definitions_in_terms_of_logarithms

See also:

addButton top

Description

Add a button below your figure that can trigger event-based code, which is especially important if you want your graphics to be useable by users who don't have, or cannot use, a mouse.

onClick is similar to the standard JS event handler, except that the call argument is a reference to your button, not the click event.

Examples

const colors = [`white`, `black`]; let bgColor = 0; function setup() { setSize(200, 200); addButton(`flip background`, (button) => { bgColor = -(bgColor - 1); redraw(); }); } function draw() { clear(colors[bgColor]); }
const colors = [`white`, `black`];
let bgColor = 0;

function setup() {
  setSize(200, 200);
  addButton(`flip background`, (button) => {
    bgColor = -(bgColor - 1);
    redraw();
  });
}

function draw() {
  clear(colors[bgColor]);
}

See also:

addSlider top

Description

Add a slider to your figure, allowing users to control a variable in your graphics code directly by interacting with that on-page slider, which is especially important if you want your graphics to be useable by users who don't have, or cannot use, a mouse.

The propLabel value should be the name of the variable that your graphics code uses, and should not be "preallocated" in your code with a const, let, or var: it will automatically get added as part of the source loading process.

The options object accepts the following properties and values:

The transform pre-processor runs after the user updates the slider, but before its value gets assigned to your variable, so that you can map it to something else (for instance, numbers in one range to numbers in a completely different range, or even numbers to strings or entire objects)

Examples

function setup() { setSize(400, 200); addSlider(`bgColor`, { min: 0, max: 255, step: 1, value: 200, transform: (v) => { // convert v into a hex color code v = v.toString(16).padStart(2, `0`); return `#${v}${v}${v}`; }, }); } function draw() { clear(bgColor); }
function setup() {
  setSize(400, 200);
  addSlider(`bgColor`, {
    min: 0,
    max: 255,
    step: 1,
    value: 200,
    transform: (v) => {
      // convert v into a hex color code
      v = v.toString(16).padStart(2, `0`);
      return `#${v}${v}${v}`;
    },
  });
}

function draw() {
  clear(bgColor);
}

See also:

arc top

  1. arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, drawWedge: boolean)
    • x - The circular center x pixel value
    • y - The circular center y pixel value
    • radius - The radius of this arc in pixels
    • startAngle - The start angle for this arc in radians
    • endAngle - The end angle for this arc in radians
    • drawWedge - A boolean indicating whether to draw a wedge or capped circle (default=circle)
  2. arc(point: PointLike, radius: number, startAngle: number, endAngle: number, drawWedge: boolean)
    • point - The circular center {x,y} coordinate
    • radius - The radius of this arc in pixels
    • startAngle - The start angle for this arc in radians
    • endAngle - The end angle for this arc in radians
    • drawWedge - A boolean indicating whether to draw a wedge or capped circle (default=circle)

Description

Draw a circular arc with radius r at (x,y), starting at angle s and ending at angle e. If wedge is true, this will draw a closed shape that is anchored at (x,y). If omitted or explicitly set to false, this will draw an open shape with a fill that connects the first and last point on the arc, but no closing stroke.

Examples

function draw() { clear(`white`); setStroke(`black`); setFill(`#F002`); arc(width / 2 + 30, height / 2 - 40, 40, 0, 0.66 * TAU); arc(width / 2 - 30, height / 2 + 20, 40, 0, 0.66 * TAU, true); }
function draw() {
  clear(`white`);
  setStroke(`black`);
  setFill(`#F002`);
  arc(width / 2 + 30, height / 2 - 40, 40, 0, 0.66 * TAU);
  arc(width / 2 - 30, height / 2 + 20, 40, 0, 0.66 * TAU, true);
}

See also:

array top

Description

Create an array of specified length, optionally filled using a function that takes the element index as single input argument.

Examples

function draw() { clear(`white`); noFill(); translate(0, height / 2); let data = array(width, (i) => [i, (height / 2) * sin(i / 25)]); plotData(data, 0, 1); }
function draw() {
  clear(`white`);
  noFill();
  translate(0, height / 2);
  let data = array(width, (i) => [i, (height / 2) * sin(i / 25)]);
  plotData(data, 0, 1);
}

asin top

Description

The inverse sine function

See also:

asinh top

Description

The hyperbolic inverse sine function

See https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions#Definitions_in_terms_of_logarithms

See also:

atan top

Description

The inverse tangent function

See also:

atan2 top

Description

The "atan2" function

See https://en.wikipedia.org/wiki/Atan2

atanh top

Description

The hyperbolic inverse tangent function

See https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions#Definitions_in_terms_of_logarithms

See also:

axes top

Description

Draw a pair of horizontal and vertical axes.

Examples

function setup() { setSize(200, 200); setBorder(1, `black`); setGrid(50, `lightgrey`); } function draw() { setCursor(`none`); clear(`#fffef7`); setColor(`#333`); translate(25, 25); axes( `time (s)`, 0, width - 50, `distance (km)`, 0, height - 50, "0", "60", "0", "500", ); }
function setup() {
  setSize(200, 200);
  setBorder(1, `black`);
  setGrid(50, `lightgrey`);
}

function draw() {
  setCursor(`none`);
  clear(`#fffef7`);
  setColor(`#333`);
  translate(25, 25);
  axes(
    `time (s)`,
    0,
    width - 50,
    `distance (km)`,
    0,
    height - 50,
    "0",
    "60",
    "0",
    "500",
  );
}

bezier top

  1. bezier(...coordinates: number[8], ...additionalCoordinates?: number[6n])
    • ...coordinates - Eight x, y values.
    • ...additionalCoordinates? - Multiples of six x, y values.
  2. bezier(...coordinates: PointLike[4], ...additionalCoordinates?: PointLike[3n])
    • ...coordinates - Four {x,y} coordinates.
    • ...additionalCoordinates? - Multiples of three {x,y} coordinates.

Description

Draw one or more Bezier curves from an array of Point or Point-likes that implement:

{
  x: number
  y: number
}

Examples

function draw() { clear(`white`); setStroke(`black`); setFill(`#F002`); bezier( new Point(20, height - 55), new Point(20, 25), { x: width - 20, y: 25 }, { x: width - 20, y: height - 55 }, ); noFill(); bezier( new Point(0, height - 20), new Point(width - 20, height - 20), { x: 20, y: 20 }, { x: width, y: 20 }, ); }
function draw() {
  clear(`white`);
  setStroke(`black`);
  setFill(`#F002`);
  bezier(
    new Point(20, height - 55),
    new Point(20, 25),
    { x: width - 20, y: 25 },
    { x: width - 20, y: height - 55 },
  );
  noFill();
  bezier(
    new Point(0, height - 20),
    new Point(width - 20, height - 20),
    { x: 20, y: 20 },
    { x: width, y: 20 },
  );
}

See also:

binomial top

Description

Get the binomial coefficient (n choose k).

bspline top

  1. bspline(...coordinates: number[8], ...additionalCoordinates?: number[2n])
    • ...coordinates - Eight x, y values.
    • ...additionalCoordinates? - Multiples of x, y values.
  2. bspline(...coordinates: PointLike[4], ...additionalCoordinates?: PointLike[n])
    • ...coordinates - Four {x,y} coordinates.
    • ...additionalCoordinates? - Zero or more {x,y} coordinates.

Description

Draw a B-spline using four or more Point or Point-likes that implement:

{
  x: number
  y: number
}

Examples

const points = []; function setup() { setSize(200, 200); range(0, TAU, PI / 5, (a) => points.push(new Point(random(30) + 50 * cos(a), random(30) + 50 * sin(a))), ); setMovable(...points); } function draw() { clear(`white`); translate(width / 2, height / 2); noStroke(); setFill(`#0002`); bspline(...points); setColor(`red`); points.forEach((p) => point(p)); }
const points = [];

function setup() {
  setSize(200, 200);
  range(0, TAU, PI / 5, (a) =>
    points.push(new Point(random(30) + 50 * cos(a), random(30) + 50 * sin(a))),
  );
  setMovable(...points);
}

function draw() {
  clear(`white`);
  translate(width / 2, height / 2);
  noStroke();
  setFill(`#0002`);
  bspline(...points);
  setColor(`red`);
  points.forEach((p) => point(p));
}

See also:

cbrt top

Description

The cube root function

See also:

ceil top

Description

The "round up to the nearest integer" function.

See also:

center top

Description

Centers the coordinate system on your graphic. This is equivalent to calling:

translate(width/2, height/2);

Examples

function draw() { clear(`white`); setColor(`red`); center(); setColor(`black`); line(0, -huge, 0, huge); line(-huge, 0, huge, 0); setColor(randomColor()); point(10, 10); setColor(randomColor()); point(10, -10); setColor(randomColor()); point(-10, -10); setColor(randomColor()); point(-10, 10); }
function draw() {
  clear(`white`);
  setColor(`red`);
  center();
  setColor(`black`);
  line(0, -huge, 0, huge);
  line(-huge, 0, huge, 0);
  setColor(randomColor());
  point(10, 10);
  setColor(randomColor());
  point(10, -10);
  setColor(randomColor());
  point(-10, -10);
  setColor(randomColor());
  point(-10, 10);
}

circle top

  1. circle(x: number, y: number, r: number)
    • x - The circle's center x pixel value
    • y - The circle's center y pixel value
    • r - The circle's radius in pixels
  2. circle(p: PointLike, r: number)
    • p - The circle's center {x,y} coordinate
    • r - The circle's radius in pixels

Description

Draw a circle with radius r at x,y.

Examples

function draw() { clear(`white`); setStroke(`black`); setFill(`#F002`); circle(width / 2, height / 2, 80); }
function draw() {
  clear(`white`);
  setStroke(`black`);
  setFill(`#F002`);
  circle(width / 2, height / 2, 80);
}

See also:

clear top

Description

Clear the canvas, and set it to a specific (CSS) colour. If no noGrid() call was made, this will then also draw the background grid.

Examples

function draw() { clear(`pink`); }
function draw() {
  clear(`pink`);
}

clearButtons top

Description

Remove all buttons for your figure from the page.

Examples

function setup() { setSize(200, 200); addButton(`this does nothing`, () => {}); } function draw() { clear(`white`); setColor(`black`); setFontSize(25); setTextAlign(CENTER, MIDDLE); text(`click to clear`, width / 2, height / 2); } function pointerDown() { clearButtons(); }
function setup() {
  setSize(200, 200);
  addButton(`this does nothing`, () => {});
}

function draw() {
  clear(`white`);
  setColor(`black`);
  setFontSize(25);
  setTextAlign(CENTER, MIDDLE);
  text(`click to clear`, width / 2, height / 2);
}

function pointerDown() {
  clearButtons();
}

See also:

clearMovable top

Description

Empty the list of movable points in your graphic.

Examples

const points = []; function setup() { setSize(200, 200); addButton(`lock`, () => { clearMovable(); redraw(); }); } function draw() { clear(`white`); for (let p of points) { setColor(isMovable(p) ? `red` : `grey`); point(p); } } function pointerDown(x, y) { if (currentMovable) return; const p = new Point(x, y); points.push(p); setMovable(p); redraw(); }
const points = [];

function setup() {
  setSize(200, 200);
  addButton(`lock`, () => {
    clearMovable();
    redraw();
  });
}

function draw() {
  clear(`white`);
  for (let p of points) {
    setColor(isMovable(p) ? `red` : `grey`);
    point(p);
  }
}

function pointerDown(x, y) {
  if (currentMovable) return;
  const p = new Point(x, y);
  points.push(p);
  setMovable(p);
  redraw();
}

See also:

clearSliders top

Description

Remove all sliders for your figure from the page.

Examples

function setup() { setSize(200, 200); addSlider(`x`); } function draw() { clear(`white`); setColor(`black`); setFontSize(25); setTextAlign(CENTER, MIDDLE); text(`click to clear`, width / 2, height / 2); } function pointerDown() { clearSliders(); }
function setup() {
  setSize(200, 200);
  addSlider(`x`);
}

function draw() {
  clear(`white`);
  setColor(`black`);
  setFontSize(25);
  setTextAlign(CENTER, MIDDLE);
  text(`click to clear`, width / 2, height / 2);
}

function pointerDown() {
  clearSliders();
}

See also:

clz32 top

Description

Get the number of leading zero bits in the 32-bit binary representation of a number

color top

Description

Generates a color based on the HSL color space.

Examples

function draw() { clear(color(45, 80, 90)); }
function draw() {
  clear(color(45, 80, 90));
}

See also:

constrain top

Description

Constrain a number to within a given range. This is really nothing more than a convenient function wrapper around the statement:

v < s ? s : v > e ? e : v

See also:

copy top

Description

Create a copy of the current canvas element for use somewhere else in your own code.

Examples

function draw() { clear(`pink`); } function pointerDown(x, y) { document.dispatchEvent( new CustomEvent(`graphics:update`, { detail: { canvas: copy(), }, }), ); }
function draw() {
  clear(`pink`);
}

function pointerDown(x, y) {
  document.dispatchEvent(
    new CustomEvent(`graphics:update`, {
      detail: {
        canvas: copy(),
      },
    }),
  );
}

cos top

Description

The cosine function

See also:

cosh top

Description

The hyperbolic cosine function

See https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions#Definitions_in_terms_of_logarithms

See also:

csc top

Description

The cosecant function, which is:

1 / sin(v)

See also:

ctn top

Description

The cotangent function, which is:

cos(v) / sin(v)

See also:

currentMovable top

constant

Description

If any points were registered as movable, and the pointer is near enough to a movable point, this value will point to that movable point, or false if the pointer is not near any movable point (or, of course, there are no movable points)

degrees top

Description

Convert a number in radians to a number in degrees. This is really nothing more than a convenient function wrapper around the statement:

v/PI * 180

With one trick, in that it allows you to constrain the resultant value to the standard [0, 360] interval.

See also:

dist top

  1. dist(x1: number, y1: number, x2: number, y2: number): number
    • x1 - The first point's x pixel value
    • y1 - The first point's y pixel value
    • x2 - The second point's x pixel value
    • y2 - The second point's y pixel value

    returns the euclidean distance between the two coordinates (number)

  2. dist(p1: PointLike, p2: PointLike): number
    • p1 - The first point's {x,y} coordinate
    • p2 - The second point's {x,y} coordinate

    returns the euclidean distance between the two coordinates (number)

Description

Calculate the 2D Euclidean distance between two points.

E top

constant

Description

The base for the natural logarithm.

See https://en.wikipedia.org/wiki/E_(mathematical_constant)

end top

Description

Counterpart to start(), finalizes the current shape and colours it. If close is true, it will close the path before colouring.

If noFill() is in effect, the shape will not be filled. if noStroke() is in effect, the shape outline will not be coloured.

Examples

function draw() { clear(`white`); setStroke(`black`); setFill(`gold`); start(); vertex(0, height / 2); vertex(width / 2, 0); vertex(width, height / 2); vertex(width / 2, height); end(true); }
function draw() {
  clear(`white`);
  setStroke(`black`);
  setFill(`gold`);
  start();
  vertex(0, height / 2);
  vertex(width / 2, 0);
  vertex(width, height / 2);
  vertex(width / 2, height);
  end(true);
}

See also:

endShape top

Description

Clear the current shape, optionally closing it.

See also:

epsilon top

constant

Description

A very small value for performing imprecise math operations such as checking whether a value is approximately the same as some other value.

exp top

Description

The exponent function, that is: e^x

See also:

find top

Description

Find an HTML element inside your graphics-element by query selector. This is equivalent to:

yourElement.querySelector(qs)

findAll top

Description

Find all HTML elements inside your graphics-element that match a given query selector. This is equivalent to:

Array.from(yourElement.querySelectorAll(qs))

floor top

Description

The "round down to the nearest integer" function.

See also:

frame top

constant

Description

The current frame number

frameDelta top

constant

Description

The number of milliseconds since the last frame.

fround top

Description

Round a number to the nearest 32 bit, rather than the standard JS 64 bit, floating point representation.

See also:

height top

constant

Description

The height of the canvas in pixels

highlight top

Description

Mark a specific color as the highlight color, which causes the graphic to redraw with that color replaced by whichever color you picked as highlight color.

Note that you can only use named (CSS) colors with this function.

Examples

function setup() { setSize(200, 200); setHighlightColor(`lime`); } function draw() { clear(); setColor(`red`); setFontSize(25); setTextAlign(CENTER, MIDDLE); text("let's go", width / 2, height / 2); } function pointerActive(state) { if (state) highlight(`red`); else highlight(false); }
function setup() {
  setSize(200, 200);
  setHighlightColor(`lime`);
}

function draw() {
  clear();
  setColor(`red`);
  setFontSize(25);
  setTextAlign(CENTER, MIDDLE);
  text("let's go", width / 2, height / 2);
}

function pointerActive(state) {
  if (state) highlight(`red`);
  else highlight(false);
}

See also:

huge top

constant

Description

A very large value that can still be used to draw things on the canvas (such as lines from -huge to +huge).

hypot top

Description

The Euclidean hypotenuse function

image top

  1. image(imgOrURL: Image|string, x: number, y: number, w: number, h: number): Image
    • imgOrURL - The image to draw either as Image object, or image URL.
    • x - The draw position's x pixel value
    • y - The draw position's y pixel value
    • w - The width over which to draw the image
    • h - The height over which to draw the image

    returns the drawn image (Image)

  2. image(imgOrURL: Image|string, p: PointLike, w: number, h: number): Image
    • imgOrURL - The image to draw either as Image object, or image URL.
    • p - The draw position as {x,y} coordinate
    • w - The width over which to draw the image
    • h - The height over which to draw the image

    returns the drawn image (Image)

Description

Draw an image in a given location with an optional width and height. If omitted, the width and height will be the image's own dimensions. Note that the image may be either a URL, or an element.

Note that this is an async function: if it is important that nothing gets drawn until the image has been drawn, remember to await its call.

Examples

async function draw() { clear(`white`); await image(`https://dummyimage.com/100x100`, 50, 50, 100, 100); }
async function draw() {
  clear(`white`);
  await image(`https://dummyimage.com/100x100`, 50, 50, 100, 100);
}

imul top

Description

The 32 bit integer multiplication function.

invertMatrix top

Description

Invert a matrix, or undefined if the matrix is not invertible.

isMovable top

Description

Check whether a point is registered as movable.

Examples

const points = []; function setup() { setSize(200, 200); addButton(`lock`, () => { clearMovable(); redraw(); }); } function draw() { clear(`white`); for (let p of points) { setColor(isMovable(p) ? `red` : `grey`); point(p); } } function pointerDown(x, y) { if (currentMovable) return; const p = new Point(x, y); points.push(p); setMovable(p); redraw(); }
const points = [];

function setup() {
  setSize(200, 200);
  addButton(`lock`, () => {
    clearMovable();
    redraw();
  });
}

function draw() {
  clear(`white`);
  for (let p of points) {
    setColor(isMovable(p) ? `red` : `grey`);
    point(p);
  }
}

function pointerDown(x, y) {
  if (currentMovable) return;
  const p = new Point(x, y);
  points.push(p);
  setMovable(p);
  redraw();
}

See also:

keyboard top

constant

Description

The keyboard object is a truth table that can be checked to see if any key is currently pressed, and if so, when that keypress was initiated, by storing:

{
  [key:string]: datetime
}

When a key is released, its mapping is removed entirely, rather than it being set to a falsey value.

line top

  1. line(x1: number, y1: number, x2: number, y2: number)
    • x1 - The first point's x pixel value
    • y1 - The first point's y pixel value
    • x2 - The second point's x pixel value
    • y2 - The second point's y pixel value
  2. line(p1: PointLike, p2: PointLike)
    • p1 - The first point's {x,y} coordinate
    • p2 - The second point's {x,y} coordinate

Description

Draw a line from one coordinate to another.

Examples

function draw() { clear(`white`); setStroke(`black`); range(0, height, 20, (i) => line(0, 0, width, i)); }
function draw() {
  clear(`white`);
  setStroke(`black`);
  range(0, height, 20, (i) => line(0, 0, width, i));
}

lli top

  1. lli(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): PointLike|false
    • x1 - The first point's x coordinate
    • y1 - The first point's y coordinate
    • x2 - The second point's x coordinate
    • y2 - The second point's y coordinate
    • x3 - The third point's x coordinate
    • y3 - The third point's y coordinate
    • x4 - The fourth point's x coordinate
    • y4 - The fourth point's y coordinate

    returns either the intersection point, or false if there is no intersection (PointLike|false)

  2. lli(p1: PointLine, p2: PointLine, p3: PointLine, p4: PointLine): PointLike|false
    • p1 - The first coordinate
    • p2 - The second coordinate
    • p3 - The third coordinate
    • p4 - The fourth coordinate

    returns either the intersection point, or false if there is no intersection (PointLike|false)

Description

Performs a line/line intersection test give either four points defining the lines (p1--p2) and (p3--p4), or eight coordinates spanning lines (x1,y1)--(x2,y2) and (x3,y3)--(x4,y4).

This function covers both "line/line" and "segment"/"segment" testing by setting a boolean value inBounds on the result: when false, there is only a line/line intersection, but when true, the actual line segments intersect.

Examples

function draw() { clear(); center(); // ...code goes here... }
function draw() {
  clear();
  center();
  // ...code goes here...
}

ln top

Description

The natural logarithm function, i.e. the base-E logarithm

(Note that in JS this function is called "log" rather than "ln")

See also:

log top

Description

The "common logarithm" function, i.e. the base-10 logarithm.

(Note that in JS this function is called "log10" rather than "log")

See also:

log2 top

Description

The binary logarithm function, i.e. the base-2 logarithm.

See also:

map top

Description

Map a value from one interval to another, optionally constrained to the target interval.

See also:

max top

Description

Find the maximum value in a set of numbers

See also:

millis top

Description

Get the number of milliseconds that this graphic has been running.

Examples

function setup() { setSize(200, 200); setColor(`black`); play(); } function draw() { clear(); setFontSize(25); setTextAlign(CENTER, MIDDLE); const seconds = (millis() / 1000) | 0; text(`${seconds}s`, width / 2, height / 2); }
function setup() {
  setSize(200, 200);
  setColor(`black`);
  play();
}

function draw() {
  clear();
  setFontSize(25);
  setTextAlign(CENTER, MIDDLE);
  const seconds = (millis() / 1000) | 0;
  text(`${seconds}s`, width / 2, height / 2);
}

min top

Description

Find the minimum value in a set of numbers

See also:

multiplyMatrix top

Description

Multiply two matrices

newSegment top

Description

Start a new segment in a shape.

See also:

noBorder top

Description

Ensure that there is no border around the canvas element.

Examples

function setup() { setSize(200, 200); setBorder(5, `red`); } function draw() { clear(`white`); setColor(`black`); setTextAlign(CENTER, MIDDLE); setFontSize(25); text(`click me`, width / 2, height / 2); } function pointerUp(x, y) { setBorder(5, `red`); redraw(); } function pointerDown(x, y) { noBorder(); redraw(); }
function setup() {
  setSize(200, 200);
  setBorder(5, `red`);
}

function draw() {
  clear(`white`);
  setColor(`black`);
  setTextAlign(CENTER, MIDDLE);
  setFontSize(25);
  text(`click me`, width / 2, height / 2);
}

function pointerUp(x, y) {
  setBorder(5, `red`);
  redraw();
}

function pointerDown(x, y) {
  noBorder();
  redraw();
}

See also:

noColor top

Description

Disable both stroke and fill color.

Examples

function draw() { clear(`white`); setColor(`black`); setTextAlign(CENTER, MIDDLE); setFontSize(25); text(`Now you see me`, width / 2, height / 2 - 25); noColor(); text(`Now you don't`, width / 2, height / 2 + 25); }
function draw() {
  clear(`white`);
  setColor(`black`);
  setTextAlign(CENTER, MIDDLE);
  setFontSize(25);
  text(`Now you see me`, width / 2, height / 2 - 25);
  noColor();
  text(`Now you don't`, width / 2, height / 2 + 25);
}

See also:

noCursor top

Description

Hide the cursor.

Examples

function draw() { clear(`white`); setColor(`#FF02`); rect(0, 0, width / 2, height); setColor(`#0FF2`); rect(width / 2, 0, width / 2, height); } function pointerMove(x, y) { if (x < width / 2) { setCursor(AUTO); } else { noCursor(); } }
function draw() {
  clear(`white`);
  setColor(`#FF02`);
  rect(0, 0, width / 2, height);
  setColor(`#0FF2`);
  rect(width / 2, 0, width / 2, height);
}

function pointerMove(x, y) {
  if (x < width / 2) {
    setCursor(AUTO);
  } else {
    noCursor();
  }
}

See also:

noFill top

Description

Disable the fill color.

Examples

function draw() { clear(`white`); setTextAlign(CENTER, MIDDLE); setFontSize(25); setTextStroke(1); setColor(`black`); rect(20, 70, 20, 20); text(`filled`, width / 2, height / 2 - 25); noFill(); rect(30, 80, 20, 20); text(`not filled`, width / 2, height / 2 + 25); }
function draw() {
  clear(`white`);
  setTextAlign(CENTER, MIDDLE);
  setFontSize(25);
  setTextStroke(1);
  setColor(`black`);
  rect(20, 70, 20, 20);
  text(`filled`, width / 2, height / 2 - 25);
  noFill();
  rect(30, 80, 20, 20);
  text(`not filled`, width / 2, height / 2 + 25);
}

See also:

noGrid top

Description

Disable the default grid background.

Examples

function draw() { clear(`white`); setColor(`black`); setTextAlign(CENTER, MIDDLE); setFontSize(25); text(`click me`, width / 2, height / 2); } function pointerUp(x, y) { setGrid(20, `lightgrey`); redraw(); } function pointerDown(x, y) { noGrid(); redraw(); }
function draw() {
  clear(`white`);
  setColor(`black`);
  setTextAlign(CENTER, MIDDLE);
  setFontSize(25);
  text(`click me`, width / 2, height / 2);
}

function pointerUp(x, y) {
  setGrid(20, `lightgrey`);
  redraw();
}

function pointerDown(x, y) {
  noGrid();
  redraw();
}

See also:

noLineDash top

Description

Set the line stroke to "solid".

Examples

function draw() { clear(`white`); setColor(`black`); setLineDash(1); line(0, 20, width, 50); setLineDash(5); line(0, 30, width, 90); setLineDash(1, 2, 3, 4); line(0, 40, width, 130); noLineDash(); line(0, 50, width, 180); }
function draw() {
  clear(`white`);
  setColor(`black`);
  setLineDash(1);
  line(0, 20, width, 50);
  setLineDash(5);
  line(0, 30, width, 90);
  setLineDash(1, 2, 3, 4);
  line(0, 40, width, 130);
  noLineDash();
  line(0, 50, width, 180);
}

See also:

noStroke top

Description

Disable the stroke color.

Examples

function draw() { clear(`white`); setTextAlign(CENTER, MIDDLE); setFontSize(25); setTextStroke(1); setColor(`red`); setStroke(`black`); rect(20, 70, 20, 20); text(`stroked`, width / 2, height / 2 - 25); noStroke(); rect(42, 82, 20, 20); text(`not stroked`, width / 2, height / 2 + 25); }
function draw() {
  clear(`white`);
  setTextAlign(CENTER, MIDDLE);
  setFontSize(25);
  setTextStroke(1);
  setColor(`red`);
  setStroke(`black`);
  rect(20, 70, 20, 20);
  text(`stroked`, width / 2, height / 2 - 25);
  noStroke();
  rect(42, 82, 20, 20);
  text(`not stroked`, width / 2, height / 2 + 25);
}

See also:

noTextStroke top

Description

Disable text stroking, but not regular shape stroking.

Examples

function draw() { clear(`white`); setTextAlign(CENTER, MIDDLE); setFontSize(25); setTextStroke(1); setColor(`red`); setStroke(`black`); rect(20, 70, 20, 20); text(`stroked`, width / 2, height / 2 - 25); noTextStroke(); rect(42, 82, 20, 20); text(`not stroked`, width / 2, height / 2 + 25); }
function draw() {
  clear(`white`);
  setTextAlign(CENTER, MIDDLE);
  setFontSize(25);
  setTextStroke(1);
  setColor(`red`);
  setStroke(`black`);
  rect(20, 70, 20, 20);
  text(`stroked`, width / 2, height / 2 - 25);
  noTextStroke();
  rect(42, 82, 20, 20);
  text(`not stroked`, width / 2, height / 2 + 25);
}

See also:

pause top

Description

Pause the graphic if its currently playing.

Examples

function setup() { setSize(200, 200); setColor(`black`); play(); } function draw() { clear(); setFontSize(25); setTextAlign(CENTER, MIDDLE); const seconds = (millis() / 1000).toFixed(1); text(`${seconds}s`, width / 2, height / 2); } function pointerActive(state) { if (state) { pause(); } else { play(); } }
function setup() {
  setSize(200, 200);
  setColor(`black`);
  play();
}

function draw() {
  clear();
  setFontSize(25);
  setTextAlign(CENTER, MIDDLE);
  const seconds = (millis() / 1000).toFixed(1);
  text(`${seconds}s`, width / 2, height / 2);
}

function pointerActive(state) {
  if (state) {
    pause();
  } else {
    play();
  }
}

See also:

PI top

constant

Description

The ratio of a circle's circumference to its diameter.

See https://en.wikipedia.org/wiki/Pi

See also:

play top

Description

Start playing your graphic, meaning it will call draw() at whatever rate the requestAnimationFrame loop is allowed to run on your computer.

Examples

let fps = 0; let checked = false; let lastFrameCheck = 0; function setup() { setSize(200, 200); setColor(`black`); play(); } function draw() { clear(); setFontSize(25); setTextAlign(CENTER, MIDDLE); const seconds = (millis() / 1000).toFixed(1); text(`fps: ${fps}`, width / 2, height / 2); if (seconds.endsWith(`.0`)) { if (!checked) { checked = true; fps = frame - lastFrameCheck; lastFrameCheck = frame; } } else { checked = false; } }
let fps = 0;
let checked = false;
let lastFrameCheck = 0;

function setup() {
  setSize(200, 200);
  setColor(`black`);
  play();
}

function draw() {
  clear();
  setFontSize(25);
  setTextAlign(CENTER, MIDDLE);
  const seconds = (millis() / 1000).toFixed(1);
  text(`fps: ${fps}`, width / 2, height / 2);
  if (seconds.endsWith(`.0`)) {
    if (!checked) {
      checked = true;
      fps = frame - lastFrameCheck;
      lastFrameCheck = frame;
    }
  } else {
    checked = false;
  }
}

See also:

playing top

constant

Description

The current play state

plot top

Description

Plot a y=f(x) function. The input to the function will span the interval [a,b] using the indicated number of steps, and the re sult may be scaled both in the x and y direction in order to draw something that you can actually see (e.g. if you're plotting to the domain [0,1] you wouldn't be able to see the result without scaling).

This function is aware of, and will plot, discontinuities using the standard open circle notation, unless instructed not to do so using the ignoreDiscontinuity boolean flag.

Examples

function draw() { clear(`white`); noFill(); setStroke(`black`); translate(0, height / 2); const fn = (x) => cos(x) ** 6 / sin(x) - sin(x) / 2; plot(fn, 0, 2 * TAU, 120, width / TAU, height / 2); }
function draw() {
  clear(`white`);
  noFill();
  setStroke(`black`);
  translate(0, height / 2);
  const fn = (x) => cos(x) ** 6 / sin(x) - sin(x) / 2;
  plot(fn, 0, 2 * TAU, 120, width / TAU, height / 2);
}

See also:

plotData top

Description

Plot a 2D graph using a collection of any-dimensional data, by indicating which dimension should be treated as the x and which dimension should be treated as the y. If no x and y are provided, data will be treated a 1D array and will plot with the array index as x and element at that index as y.

Examples

function draw() { clear(`white`); noFill(); translate(0, height / 2); setStroke(`darkgreen`); let data = array(width, (i) => [i, (height / 2) * sin(i / 25)]); plotData(data, 0, 1); setStroke(`purple`); data = array(width, (i) => ({ meep: i, moop: (height / 2) * cos(i / 25), })); plotData(data, `meep`, `moop`); }
function draw() {
  clear(`white`);
  noFill();
  translate(0, height / 2);

  setStroke(`darkgreen`);
  let data = array(width, (i) => [i, (height / 2) * sin(i / 25)]);
  plotData(data, 0, 1);

  setStroke(`purple`);
  data = array(width, (i) => ({
    meep: i,
    moop: (height / 2) * cos(i / 25),
  }));
  plotData(data, `meep`, `moop`);
}

See also:

point top

  1. point(x: number, y: number)
    • x - The point's center x pixel value
    • y - The point's center y pixel value
  2. point(p: PointLike)
    • p - The point's center {x,y} coordinate

Description

Draw a point (either from x/y or point-like).

Examples

function draw() { clear(`white`); translate(width / 2, height / 2); range(0, TAU, (a) => { point(40 * cos(a), 40 * sin(a)); }); }
function draw() {
  clear(`white`);
  translate(width / 2, height / 2);
  range(0, TAU, (a) => {
    point(40 * cos(a), 40 * sin(a));
  });
}

See also:

pointer top

constant

Description

The pointer object represents the mouse cursor (when using a mouse) or finger position (for touch devices), and models several aspects:

pow top

Description

The power function.

Note that this function is a holdover from before JS had the ** operator for performing this calculation.

project top

  1. project(x: number, y: number, z: number): PointLike
    • x - The 3D coordinate's x value
    • y - The 3D coordinate's x value
    • z - The 3D coordinate's x value

    returns p The projected 2D {x,y} coordinate (PointLike)

  2. project(p: PointLike): PointLike
    • p - The 2D coordinate as {x,y,z} coordinate

    returns p The projected 2D {x,y} coordinate (PointLike)

Description

Project a 3D coordinate to 2D.

Examples

function setup() { setSize(200, 200); setProjector(width / 2, height / 2, 50, -0.4); } function draw() { clear(`white`); setColor(`red`); line(project(-1, -1, -1), project(1, -1, -1)); line(project(-1, -1, 1), project(1, -1, 1)); line(project(-1, 1, -1), project(1, 1, -1)); line(project(-1, 1, 1), project(1, 1, 1)); setColor(`blue`); line(project(-1, -1, -1), project(-1, -1, 1)); line(project(-1, 1, -1), project(-1, 1, 1)); line(project(1, -1, -1), project(1, -1, 1)); line(project(1, 1, -1), project(1, 1, 1)); setColor(`green`); line(project(1, 1, -1), project(1, -1, -1)); line(project(1, 1, 1), project(1, -1, 1)); line(project(-1, 1, -1), project(-1, -1, -1)); line(project(-1, 1, 1), project(-1, -1, 1)); }
function setup() {
  setSize(200, 200);
  setProjector(width / 2, height / 2, 50, -0.4);
}

function draw() {
  clear(`white`);
  setColor(`red`);
  line(project(-1, -1, -1), project(1, -1, -1));
  line(project(-1, -1, 1), project(1, -1, 1));
  line(project(-1, 1, -1), project(1, 1, -1));
  line(project(-1, 1, 1), project(1, 1, 1));
  setColor(`blue`);
  line(project(-1, -1, -1), project(-1, -1, 1));
  line(project(-1, 1, -1), project(-1, 1, 1));
  line(project(1, -1, -1), project(1, -1, 1));
  line(project(1, 1, -1), project(1, 1, 1));
  setColor(`green`);
  line(project(1, 1, -1), project(1, -1, -1));
  line(project(1, 1, 1), project(1, -1, 1));
  line(project(-1, 1, -1), project(-1, -1, -1));
  line(project(-1, 1, 1), project(-1, -1, 1));
}

See also:

radians top

Description

Convert a number in degrees to a number in radians. This is really nothing more than a convenient function wrapper around the statement:

v/180 * PI

With one trick, in that it allows you to constrain the resultant value to the standard [0, TAU] interval.

See also:

random top

  1. random(): number

      returns a random number in the interval [0,1) (number)

    • random(a: number): number
      • a - The upper bound for the random number

      returns a random number in the interval [0,a) (number)

    • random(a: number, b: number): number
      • a - The lower bound for the random number
      • b - The upper bound for the random number

      returns a random number in the interval [a, b) (number)

    Description

    Generate a pseudo-random number.

    This is based on the SplitMix32 algorithm, covered over on https://stackoverflow.com/a/47593316/740553

    Examples

    function draw() { clear(`white`); setColor(`black`); setFontSize(20); range(0, height + 20, 20, (v) => { text(random(), 5, v); }); }
    function draw() {
      clear(`white`);
      setColor(`black`);
      setFontSize(20);
      range(0, height + 20, 20, (v) => {
        text(random(), 5, v);
      });
    }
    

    See also:

    randomColor top

    Description

    Generate a random colour. Note that this function allows you to get "the currently generated random colour" in different opacities by calling the function with an opacity value, and false as cycle argument.

    Examples

    function draw() { clear(randomColor()); } function pointerDown() { redraw(); }
    function draw() {
      clear(randomColor());
    }
    
    function pointerDown() {
      redraw();
    }
    

    See also:

    randomSeed top

    Description

    Set the pseudo-random number generator seed. If no seed value is provided, this is equivalent to calling:

    randomSeed(Date.now() * Math.random())
    

    See also:

    range top

    Description

    An alternative to writing for loops, because no one wants to constantly write var allocations that only live for the duration of a loop.

    Examples

    function draw() { clear(`white`); translate(width / 2, height / 2); range(0, TAU, (a) => point(40 * cos(a), 40 * sin(a))); }
    function draw() {
      clear(`white`);
      translate(width / 2, height / 2);
      range(0, TAU, (a) => point(40 * cos(a), 40 * sin(a)));
    }
    

    rect top

    1. rect(x: number, y: number, w: number, h: number)
      • x - The rect's corner x pixel value
      • y - The rect's corner y pixel value
      • w - The width over which to draw the image
      • h - The height over which to draw the image
    2. rect(p: PointLike, w: number, h: number)
      • p - The rect;s corder {x,y} coordinate
      • w - The width over which to draw the image
      • h - The height over which to draw the image

    Description

    Draw a rectangle at the specified coordinate, with the specific width and height.

    Examples

    function draw() { clear(`white`); setStroke(`black`); setFill(`red`); rect(40, 40, width - 80, height - 80); }
    function draw() {
      clear(`white`);
      setStroke(`black`);
      setFill(`red`);
      rect(40, 40, width - 80, height - 80);
    }
    

    redraw top

    Description

    Safely trigger a new draw pass. If the graphic is running in animated mode, or a redraw() is triggered during a redraw(), this call will do nothing.

    Examples

    function draw() { const h = map(pointer.x, 0, width, 0, 360); const l = map(pointer.y, 0, height, 50, 0); clear(color(h, 100, l)); } function pointerMove() { redraw(); }
    function draw() {
      const h = map(pointer.x, 0, width, 0, 360);
      const l = map(pointer.y, 0, height, 50, 0);
      clear(color(h, 100, l));
    }
    
    function pointerMove() {
      redraw();
    }
    

    resetTransform top

    Description

    Reset the coordinate transform matrix.

    Examples

    function setup() { setSize(200, 200); noGrid(); } function draw() { clear(`lightgrey`); setColor(`red`); translate(50, 50); line(0, 0, 100, 0); point(0, 0); setColor(`darkgreen`); point(10, 0); rotate(PI / 4); point(10, 0); line(0, 0, 100, 0); setColor(`blue`); rotate(-PI / 6); point(100, 0); scale(0.5, 0.5); point(100, 0); line(100, 0, 200, 0); resetTransform(); setColor(`black`); line(0, 3, 100, 3); point(0, 3); point(10, 3); point(100, 3); }
    function setup() {
      setSize(200, 200);
      noGrid();
    }
    
    function draw() {
      clear(`lightgrey`);
      setColor(`red`);
      translate(50, 50);
      line(0, 0, 100, 0);
      point(0, 0);
      setColor(`darkgreen`);
      point(10, 0);
      rotate(PI / 4);
      point(10, 0);
      line(0, 0, 100, 0);
      setColor(`blue`);
      rotate(-PI / 6);
      point(100, 0);
      scale(0.5, 0.5);
      point(100, 0);
      line(100, 0, 200, 0);
      resetTransform();
      setColor(`black`);
      line(0, 3, 100, 3);
      point(0, 3);
      point(10, 3);
      point(100, 3);
    }
    

    See also:

    restore top

    Description

    Restore the graphics context (transforms, current colors, etc) to what they were when save() was called.

    Examples

    const points = []; function draw() { clear(); translate(width / 2, height / 2); setColor(`blue`); line(0, 0, 80, 0); save(); setColor(`darkgreen`); range(0, 5, 1, (a) => { rotate(PI / 8); line(0, 0, 80, 0); }); restore(); line(-20, 0, -80, 0); }
    const points = [];
    
    function draw() {
      clear();
      translate(width / 2, height / 2);
      setColor(`blue`);
      line(0, 0, 80, 0);
      save();
      setColor(`darkgreen`);
      range(0, 5, 1, (a) => {
        rotate(PI / 8);
        line(0, 0, 80, 0);
      });
      restore();
      line(-20, 0, -80, 0);
    }
    

    See also:

    rotate top

    Description

    Rotate the coordinate system wrt the current origin.

    Examples

    function setup() { setSize(200, 200); noGrid(); } function draw() { clear(`lightgrey`); translate(width / 2, height / 2); setColor(`black`); point(0, 0); setColor(`darkgreen`); line(0, 0, 20, 20); point(20, 20); rotate(PI / 4); line(0, 0, 20, 20); point(20, 20); }
    function setup() {
      setSize(200, 200);
      noGrid();
    }
    
    function draw() {
      clear(`lightgrey`);
      translate(width / 2, height / 2);
      setColor(`black`);
      point(0, 0);
      setColor(`darkgreen`);
      line(0, 0, 20, 20);
      point(20, 20);
      rotate(PI / 4);
      line(0, 0, 20, 20);
      point(20, 20);
    }
    

    See also:

    rotateProjector top

    Description

    Set the projector's x, y, and z axis rotation in radians. Note that these are applied in order.

    Examples

    function setup() { setSize(200, 200); setProjector(width / 2, height / 2, 50, -0.4); play(); } function draw() { clear(`white`); const m = millis() / 5000; rotateProjector(m, 2 * m, 3 * m); setColor(`red`); line(project(-1, -1, -1), project(1, -1, -1)); line(project(-1, -1, 1), project(1, -1, 1)); line(project(-1, 1, -1), project(1, 1, -1)); line(project(-1, 1, 1), project(1, 1, 1)); setColor(`blue`); line(project(-1, -1, -1), project(-1, -1, 1)); line(project(-1, 1, -1), project(-1, 1, 1)); line(project(1, -1, -1), project(1, -1, 1)); line(project(1, 1, -1), project(1, 1, 1)); setColor(`green`); line(project(1, 1, -1), project(1, -1, -1)); line(project(1, 1, 1), project(1, -1, 1)); line(project(-1, 1, -1), project(-1, -1, -1)); line(project(-1, 1, 1), project(-1, -1, 1)); }
    function setup() {
      setSize(200, 200);
      setProjector(width / 2, height / 2, 50, -0.4);
      play();
    }
    
    function draw() {
      clear(`white`);
      const m = millis() / 5000;
      rotateProjector(m, 2 * m, 3 * m);
      setColor(`red`);
      line(project(-1, -1, -1), project(1, -1, -1));
      line(project(-1, -1, 1), project(1, -1, 1));
      line(project(-1, 1, -1), project(1, 1, -1));
      line(project(-1, 1, 1), project(1, 1, 1));
      setColor(`blue`);
      line(project(-1, -1, -1), project(-1, -1, 1));
      line(project(-1, 1, -1), project(-1, 1, 1));
      line(project(1, -1, -1), project(1, -1, 1));
      line(project(1, 1, -1), project(1, 1, 1));
      setColor(`green`);
      line(project(1, 1, -1), project(1, -1, -1));
      line(project(1, 1, 1), project(1, -1, 1));
      line(project(-1, 1, -1), project(-1, -1, -1));
      line(project(-1, 1, 1), project(-1, -1, 1));
    }
    

    See also:

    round top

    Description

    The "round to the nearest integer" function, rounding any value [x.0, x.4999...] to x, and any value [x.5, x.999...] to x + 1.

    See also:

    save top

    Description

    Save the current graphics context (transforms, current colors, etc) so that those can be restored after changing them.

    Examples

    const points = []; function draw() { clear(); translate(width / 2, height / 2); setColor(`blue`); line(0, 0, 80, 0); save(); setColor(`darkgreen`); range(0, 5, 1, (a) => { rotate(PI / 8); line(0, 0, 80, 0); }); restore(); line(-20, 0, -80, 0); }
    const points = [];
    
    function draw() {
      clear();
      translate(width / 2, height / 2);
      setColor(`blue`);
      line(0, 0, 80, 0);
      save();
      setColor(`darkgreen`);
      range(0, 5, 1, (a) => {
        rotate(PI / 8);
        line(0, 0, 80, 0);
      });
      restore();
      line(-20, 0, -80, 0);
    }
    

    See also:

    scale top

    Description

    Scale the coordinate system wrt the current origin.

    Examples

    function setup() { setSize(200, 200); noGrid(); } function draw() { clear(`lightgrey`); translate(width / 2, height / 2); setColor(`black`); point(0, 0); setColor(`darkgreen`); line(0, 0, 20, 20); point(20, 20); rotate(PI / 4); scale(2); line(0, 0, 20, 20); point(20, 20); }
    function setup() {
      setSize(200, 200);
      noGrid();
    }
    
    function draw() {
      clear(`lightgrey`);
      translate(width / 2, height / 2);
      setColor(`black`);
      point(0, 0);
      setColor(`darkgreen`);
      line(0, 0, 20, 20);
      point(20, 20);
      rotate(PI / 4);
      scale(2);
      line(0, 0, 20, 20);
      point(20, 20);
    }
    

    See also:

    screenToWorld top

    1. screenToWorld(x: number, y: number): PointLike
      • x - The screen coordinate's x value in pixels
      • y - The screen coordinate's y value in pixels

      returns p The world {x,y} coordinate (PointLike)

    2. screenToWorld(p: PointLike): PointLike
      • p - The screen {x,y} coordinate

      returns p The world {x,y} coordinate (PointLike)

    Description

    Convert a screen (e.g. browser) coordinate into its corresponding "transformed" coordinate.

    Examples

    function setup() { setSize(200, 200); noGrid(); } function draw() { clear(`lightgrey`); translate(width / 2, height / 2); rotate(PI / 4); scale(0.5); if (pointer.active) { setColor(`red`); point(pointer.x, pointer.y); setColor(`blue`); point(screenToWorld(pointer.x, pointer.y)); } } function pointerMove() { redraw(); }
    function setup() {
      setSize(200, 200);
      noGrid();
    }
    
    function draw() {
      clear(`lightgrey`);
      translate(width / 2, height / 2);
      rotate(PI / 4);
      scale(0.5);
      if (pointer.active) {
        setColor(`red`);
        point(pointer.x, pointer.y);
        setColor(`blue`);
        point(screenToWorld(pointer.x, pointer.y));
      }
    }
    
    function pointerMove() {
      redraw();
    }
    

    See also:

    sec top

    Description

    The secant function, which is:

    1 / cos(v)
    

    See also:

    setBorder top

    Description

    Set a border around the canvas.

    Examples

    function setup() { setSize(200, 200); setBorder(10, `red`); }
    function setup() {
      setSize(200, 200);
      setBorder(10, `red`);
    }
    

    See also:

    setColor top

    Description

    Set the current stroke and fill colour at the same time.

    Examples

    function draw() { clear(); setColor(`blue`); rect(50, 50, 100, 100); }
    function draw() {
      clear();
      setColor(`blue`);
      rect(50, 50, 100, 100);
    }
    

    See also:

    setCursor top

    Description

    Change the cursor to a specific icon:

    Use any other string found over on the MDN cursor article to set a cursor not covered by the above constants.

    Examples

    function draw() { clear(`white`); setColor(`#FF02`); rect(0, 0, width / 2, height); setColor(`#0FF2`); rect(width / 2, 0, width / 2, height); } function pointerMove(x, y) { if (x < width / 2) { setCursor(AUTO); } else { noCursor(); } }
    function draw() {
      clear(`white`);
      setColor(`#FF02`);
      rect(0, 0, width / 2, height);
      setColor(`#0FF2`);
      rect(width / 2, 0, width / 2, height);
    }
    
    function pointerMove(x, y) {
      if (x < width / 2) {
        setCursor(AUTO);
      } else {
        noCursor();
      }
    }
    

    See also:

    setFill top

    Description

    Set the current fill colour.

    Examples

    function draw() { clear(); setStroke(`black`); setFill(`red`); rect(50, 50, 100, 100); }
    function draw() {
      clear();
      setStroke(`black`);
      setFill(`red`);
      rect(50, 50, 100, 100);
    }
    

    See also:

    setFont top

    Description

    Set the current font using a single string. For the syntax, see https://developer.mozilla.org/en-US/docs/Web/CSS/font

    See also:

    setFontFamily top

    Description

    Set the current font family.

    See also:

    setFontSize top

    Description

    Set the current font size

    See also:

    setFontWeight top

    Description

    Set the current font weight

    See also:

    setGrid top

    Description

    Set the background grid spacing and colour.

    Examples

    function setup() { setSize(200, 200); setGrid(20, `lavender`); } function draw() { clear(`white`); }
    function setup() {
      setSize(200, 200);
      setGrid(20, `lavender`);
    }
    
    function draw() {
      clear(`white`);
    }
    

    See also:

    setHighlightColor top

    Description

    Set the color that should be used to replace whatever highlight() marked as the "to highlight" color.

    Examples

    function setup() { setSize(200, 200); setHighlightColor(`lime`); } function draw() { clear(); setColor(`red`); setFontSize(25); setTextAlign(CENTER, MIDDLE); text("let's go", width / 2, height / 2); } function pointerActive(state) { if (state) highlight(`red`); else highlight(false); }
    function setup() {
      setSize(200, 200);
      setHighlightColor(`lime`);
    }
    
    function draw() {
      clear();
      setColor(`red`);
      setFontSize(25);
      setTextAlign(CENTER, MIDDLE);
      text("let's go", width / 2, height / 2);
    }
    
    function pointerActive(state) {
      if (state) highlight(`red`);
      else highlight(false);
    }
    

    See also:

    setLineDash top

    Description

    Set the line dash property. See the following MDN article for the details:

    https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash

    See also:

    setLineWidth top

    Description

    Set the line width in pixels.

    Examples

    function draw() { clear(`white`); setColor(`black`); range(1, 10, (i) => { setLineWidth(i); line(20, i * 20, 180, i * 20); }); }
    function draw() {
      clear(`white`);
      setColor(`black`);
      range(1, 10, (i) => {
        setLineWidth(i);
        line(20, i * 20, 180, i * 20);
      });
    }
    

    See also:

    setMovable top

    Description

    Mark one or more points as movable, meaning that the user can reposition the point around on the canvas by touch/click-dragging.

    Examples

    const points = []; function setup() { setSize(200, 200); for (let i = 40; i < 200; i += 20) { points.push(new Point(i - 20, 120)); } setMovable(...points); } function draw() { clear(); noFill(); setStroke(`purple`); bspline(...points); for (let p of points) point(p); }
    const points = [];
    
    function setup() {
      setSize(200, 200);
      for (let i = 40; i < 200; i += 20) {
        points.push(new Point(i - 20, 120));
      }
      setMovable(...points);
    }
    
    function draw() {
      clear();
      noFill();
      setStroke(`purple`);
      bspline(...points);
      for (let p of points) point(p);
    }
    

    See also:

    setProjector top

    Description

    Set the project parameters. Currently, only cabinet project is supported, which accepts the following parameters:

    Examples

    function setup() { setSize(200, 200); setProjector(width / 2, height / 2, 50, -0.4); } function draw() { clear(`white`); setColor(`red`); line(project(-1, -1, -1), project(1, -1, -1)); line(project(-1, -1, 1), project(1, -1, 1)); line(project(-1, 1, -1), project(1, 1, -1)); line(project(-1, 1, 1), project(1, 1, 1)); setColor(`blue`); line(project(-1, -1, -1), project(-1, -1, 1)); line(project(-1, 1, -1), project(-1, 1, 1)); line(project(1, -1, -1), project(1, -1, 1)); line(project(1, 1, -1), project(1, 1, 1)); setColor(`green`); line(project(1, 1, -1), project(1, -1, -1)); line(project(1, 1, 1), project(1, -1, 1)); line(project(-1, 1, -1), project(-1, -1, -1)); line(project(-1, 1, 1), project(-1, -1, 1)); }
    function setup() {
      setSize(200, 200);
      setProjector(width / 2, height / 2, 50, -0.4);
    }
    
    function draw() {
      clear(`white`);
      setColor(`red`);
      line(project(-1, -1, -1), project(1, -1, -1));
      line(project(-1, -1, 1), project(1, -1, 1));
      line(project(-1, 1, -1), project(1, 1, -1));
      line(project(-1, 1, 1), project(1, 1, 1));
      setColor(`blue`);
      line(project(-1, -1, -1), project(-1, -1, 1));
      line(project(-1, 1, -1), project(-1, 1, 1));
      line(project(1, -1, -1), project(1, -1, 1));
      line(project(1, 1, -1), project(1, 1, 1));
      setColor(`green`);
      line(project(1, 1, -1), project(1, -1, -1));
      line(project(1, 1, 1), project(1, -1, 1));
      line(project(-1, 1, -1), project(-1, -1, -1));
      line(project(-1, 1, 1), project(-1, -1, 1));
    }
    

    See also:

    setSize top

    Description

    Set (or change) the graphic's size. Note that your width and height values will get rounded to integer values.

    Note that setSize will immediately trigger a redraw, whether you want it to or not, because changing canvas dimensions clears the canvas, necessitating a redraw.

    Examples

    function setup() { setSize(400, 200); } function draw() { clear(); center(); setColor(`black`); setFontSize(25); text(`${width}/${height}`, 0, 0, CENTER, MIDDLE); } function pointerUp() { setSize(random(100, 400), 200); // Note that there is no redraw() here! }
    function setup() {
      setSize(400, 200);
    }
    
    function draw() {
      clear();
      center();
      setColor(`black`);
      setFontSize(25);
      text(`${width}/${height}`, 0, 0, CENTER, MIDDLE);
    }
    
    function pointerUp() {
      setSize(random(100, 400), 200);
      // Note that there is no redraw() here!
    }
    

    setStroke top

    Description

    Set the current stroke colour.

    Examples

    function draw() { clear(); setStroke(`black`); setFill(`red`); rect(50, 50, 100, 100); }
    function draw() {
      clear();
      setStroke(`black`);
      setFill(`red`);
      rect(50, 50, 100, 100);
    }
    

    See also:

    setTextAlign top

    Description

    Set the current text alignment values.

    Valid xAlign values are:

    Valid yAlign values are:

    Examples

    function draw() { clear(`white`); setFontSize(20); setColor(`black`); line(width / 2, 0, width / 2, height); line(0, height / 2, width, height / 2); setTextAlign(CENTER, MIDDLE); text("center middle", width / 2, height / 2); line(0, height / 2 - 50, width, height / 2 - 50); setTextAlign(RIGHT, TOP); text("right top", width / 2, height / 2 - 50); line(0, height / 2 + 50, width, height / 2 + 50); setTextAlign(LEFT, BOTTOM); text("left bottom", width / 2, height / 2 + 50); }
    function draw() {
      clear(`white`);
      setFontSize(20);
      setColor(`black`);
      line(width / 2, 0, width / 2, height);
      line(0, height / 2, width, height / 2);
      setTextAlign(CENTER, MIDDLE);
      text("center middle", width / 2, height / 2);
      line(0, height / 2 - 50, width, height / 2 - 50);
      setTextAlign(RIGHT, TOP);
      text("right top", width / 2, height / 2 - 50);
      line(0, height / 2 + 50, width, height / 2 + 50);
      setTextAlign(LEFT, BOTTOM);
      text("left bottom", width / 2, height / 2 + 50);
    }
    

    setTextStroke top

    Description

    Set the text outline stroking properties.

    Examples

    function draw() { clear(`white`); setFontSize(25); setTextStroke(`red`, 1); setFill(`yellow`); text("fancy text", width / 2, 80, CENTER, CENTER); setFontSize(65); setTextStroke(`red`, 3); setFill(`yellow`); text("fancy text", width / 2, 140, CENTER, CENTER); }
    function draw() {
      clear(`white`);
      setFontSize(25);
      setTextStroke(`red`, 1);
      setFill(`yellow`);
      text("fancy text", width / 2, 80, CENTER, CENTER);
      setFontSize(65);
      setTextStroke(`red`, 3);
      setFill(`yellow`);
      text("fancy text", width / 2, 140, CENTER, CENTER);
    }
    

    See also:

    sign top

    Description

    Get the sign of a number

    sin top

    Description

    The sine function

    See also:

    sinh top

    Description

    The hyperbolic sine function

    See https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions#Definitions_in_terms_of_logarithms

    See also:

    spline top

    Description

    Draw a cardinal (hermite) spline that passes through each point provided, using a mathematically virtual start and end to ensure the curve starts and ends at the provided start and end point. This can be bypassed by setting the virtual argument to false.

    Additionally, the spline's tightness, which controls how "bendy" the spline is (the tighter the spline, the sharper bends become) can be controlled by setting the tightness value.

    Examples

    const points = []; function setup() { setSize(200, 200); range(0, TAU, PI / 5, (a) => points.push(new Point(random(30) + 50 * cos(a), random(30) + 50 * sin(a))), ); setMovable(...points); } function draw() { clear(`white`); translate(width / 2, height / 2); setFill(`#0002`); spline(...points); setColor(`red`); points.forEach((p) => point(p)); }
    const points = [];
    
    function setup() {
      setSize(200, 200);
      range(0, TAU, PI / 5, (a) =>
        points.push(new Point(random(30) + 50 * cos(a), random(30) + 50 * sin(a))),
      );
      setMovable(...points);
    }
    
    function draw() {
      clear(`white`);
      translate(width / 2, height / 2);
      setFill(`#0002`);
      spline(...points);
      setColor(`red`);
      points.forEach((p) => point(p));
    }
    

    See also:

    sqrt top

    Description

    The square root function.

    Note that this function is a holdover from before JS had the ** operator for performing this calculation by using x ** 0.5.

    See also:

    start top

    Description

    Starts a (new) shape.

    Examples

    function draw() { clear(`white`); setStroke(`black`); setFill(`gold`); start(); vertex(0, height / 2); vertex(width / 2, 0); vertex(width, height / 2); vertex(width / 2, height); end(true); }
    function draw() {
      clear(`white`);
      setStroke(`black`);
      setFill(`gold`);
      start();
      vertex(0, height / 2);
      vertex(width / 2, 0);
      vertex(width, height / 2);
      vertex(width / 2, height);
      end(true);
    }
    

    See also:

    startShape top

    Description

    Start a new shape. This yields a Shape object with the following API:

    A Shape also supports the following utility functions:

    And it supports the following pathing functions, with arguments that can either consist of (the necessary number of) pairs of coordinate values, or (the necessary number of) point-likes, being objects with an x and y property.

    Cardinal spline coordinates are rendered by treating the path as closed (even if it is not), performing wrap-around lookups as needed in order to draw "something sensible".

    Examples

    let shape; function setup() { setSize(200, 200); shape = startShape(); shape.allowResizing(); shape.showPoints(); shape.makeMovable(); // Create a diamond shape shape.add(10, height / 2); shape.add(width / 2, 10); shape.add(width - 10, height / 2); shape.add(width / 2, height - 10); // With a rectangular cutout shape.newSegment(true); shape.add(75, 75); shape.add(125, 75); shape.add(125, 125); shape.add(75, 125); shape.flipSegment(); shape.close(); shape.setStroke(`black`); shape.setFill(`gold`); } function draw() { clear(`white`); shape.draw(true); }
    let shape;
    function setup() {
      setSize(200, 200);
      shape = startShape();
      shape.allowResizing();
      shape.showPoints();
      shape.makeMovable();
      // Create a diamond shape
      shape.add(10, height / 2);
      shape.add(width / 2, 10);
      shape.add(width - 10, height / 2);
      shape.add(width / 2, height - 10);
      // With a rectangular cutout
      shape.newSegment(true);
      shape.add(75, 75);
      shape.add(125, 75);
      shape.add(125, 125);
      shape.add(75, 125);
      shape.flipSegment();
      shape.close();
      shape.setStroke(`black`);
      shape.setFill(`gold`);
    }
    function draw() {
      clear(`white`);
      shape.draw(true);
    }
    

    See also:

    tan top

    Description

    The tangent function

    tanh top

    Description

    The hyperbolic tangent function

    See https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions#Definitions_in_terms_of_logarithms

    See also:

    TAU top

    constant

    Description

    The ratio of a circle's circumference to its radius, i.e. 2*PI

    See https://en.wikipedia.org/wiki/Turn_(angle)#Tau_proposals

    See also:

    text top

    1. text(str: string, x: number, y: number, xAlign?: string, yAlign?: string)
      • str - The text we want to show
      • x - The text location's x pixel value
      • y - The text location's y pixel value
      • xAlign? - An optional horizontal alignment string
      • yAlign? - An optional vertical alignment string
    2. text(str: string, p: PointLike, xAlign?: string, yAlign?: string)
      • str - The text we want to show
      • p - The text location's {x,y} coordinate
      • xAlign? - An optional horizontal alignment string
      • yAlign? - An optional vertical alignment string

    Description

    Draw some text to the screen. Its placement is determined by both the coordinate provided, and the x/y alignment provided. Valid xAlign values are:

    Valid yAlign values are:

    Note that the primary text colour uses the fill colour. If text stroking is enabled, the the text outline will be coloured using the current stroke colour.

    Examples

    function draw() { clear(`white`); setColor(`black`); setFontSize(25); text("normal text", width / 2, 60, CENTER, CENTER); noFill(); setTextStroke(1); text("unfilled text", width / 2, 100, CENTER, CENTER); setStroke(`red`); setFill(`yellow`); text("fancy text", width / 2, 140, CENTER, CENTER); }
    function draw() {
      clear(`white`);
      setColor(`black`);
      setFontSize(25);
      text("normal text", width / 2, 60, CENTER, CENTER);
      noFill();
      setTextStroke(1);
      text("unfilled text", width / 2, 100, CENTER, CENTER);
      setStroke(`red`);
      setFill(`yellow`);
      text("fancy text", width / 2, 140, CENTER, CENTER);
    }
    

    See also:

    toDataURL top

    Description

    Convert the current canvas into an data URL that represents a PNG image.

    togglePlay top

    Description

    If the graphic is currently playing, pause it, and if it's paused, play it.

    Examples

    function setup() { setSize(200, 200); setColor(`black`); play(); } function draw() { clear(); setFontSize(25); setTextAlign(CENTER, MIDDLE); const seconds = (millis() / 1000).toFixed(1); text(`${seconds}s`, width / 2, height / 2); } function pointerActive(state) { togglePlay(); }
    function setup() {
      setSize(200, 200);
      setColor(`black`);
      play();
    }
    
    function draw() {
      clear();
      setFontSize(25);
      setTextAlign(CENTER, MIDDLE);
      const seconds = (millis() / 1000).toFixed(1);
      text(`${seconds}s`, width / 2, height / 2);
    }
    
    function pointerActive(state) {
      togglePlay();
    }
    

    See also:

    transform top

    Description

    Set the current transform matrix, based on applying:

          | a b c |
      m = | d e f |
          | 0 0 1 |
    

    With the parameters defaulting to the identity matrix.

    See the following MDN article for more details about this function: https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/transform

    See also:

    translate top

    1. translate(x: number, y: number)
      • x - The x value in pixels to be treated as the new "zero"
      • y - The y value in pixels to be treated as the new "zero"
    2. translate(p: PointLike)
      • p - The {x,y} coordinate to be treated as the new "zero"

    Description

    Translate the coordinate system by some amount of x and y units.

    Examples

    function draw() { clear(); translate(width / 2, height / 2); point(0, 0); }
    function draw() {
      clear();
      translate(width / 2, height / 2);
      point(0, 0);
    }
    

    See also:

    transposeMatrix top

    Description

    Transpose a matrix

    triangle top

    1. triangle(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number)
      • x1 - The first point's x pixel value
      • y1 - The first point's y pixel value
      • x2 - The second point's x pixel value
      • y2 - The second point's y pixel value
      • x3 - The third point's x pixel value
      • y3 - The third point's y pixel value
    2. triangle(p1: PointLike, p2: PointLike, p3: PointLike)
      • p1 - The first point's {x,y} coordinate
      • p2 - The second point's {x,y} coordinate
      • p3 - The third point's {x,y} coordinate

    Description

    Draw a triangle.

    Examples

    function draw() { clear(`white`); setStroke(`black`); setFill(`red`); triangle(width / 2, 30, (1 / 4) * width, 160, (3 / 4) * width, 110); }
    function draw() {
      clear(`white`);
      setStroke(`black`);
      setFill(`red`);
      triangle(width / 2, 30, (1 / 4) * width, 160, (3 / 4) * width, 110);
    }
    

    trunc top

    Description

    Truncate a fraction to an integer by simply dropping the fractional part. Note that this differs from the floor function:

    floor(4.2);  // 4
    floor(-4.2); // -5
    
    trunc(4.2);  // 4
    trunc(-4.2); // -4
    

    See also:

    vertex top

    1. vertex(x: number, y: number)
      • x - The vertex's x pixel value
      • y - The vertex's y pixel value
    2. vertex(p: PointLike)
      • p - The vertex {x,y} coordinate

    Description

    Add a vertex to the currently active shape.

    Examples

    function draw() { clear(`white`); setStroke(`black`); setFill(`red`); start(); vertex(width / 2, 30); vertex((1 / 4) * width, 160); vertex((3 / 4) * width, 110); end(); }
    function draw() {
      clear(`white`);
      setStroke(`black`);
      setFill(`red`);
      start();
      vertex(width / 2, 30);
      vertex((1 / 4) * width, 160);
      vertex((3 / 4) * width, 110);
      end();
    }
    

    See also:

    width top

    constant

    Description

    The width of the canvas in pixels

    worldToScreen top

    1. worldToScreen(x: number, y: number): PointLike
      • x - The world coordinate's x value in pixels
      • y - The world coordinate's y value in pixels

      returns p The screen {x,y} coordinate (PointLike)

    2. worldToScreen(p: PointLike): PointLike
      • p - The world {x,y} coordinate

      returns p The screen {x,y} coordinate (PointLike)

    Description

    Convert an in-canvas "transformed" coordinate into its corresponding "screen" (i.e. browser canvas offset) coordinate.

    Examples

    function setup() { setSize(200, 200); play(); } function draw() { clear(); translate(width / 2, height / 2); rotate(millis() / 2000); setFontSize(25); const p = new Point(30, 0); point(p); text(`${p.x},${p.y}`, p.x + 10, p.y + 10); const { x, y } = worldToScreen(p); resetTransform(); setFontSize(16); text(`${x.toFixed()},${y.toFixed()}`, x - 25, y - 15); }
    function setup() {
      setSize(200, 200);
      play();
    }
    
    function draw() {
      clear();
      translate(width / 2, height / 2);
    
      rotate(millis() / 2000);
      setFontSize(25);
      const p = new Point(30, 0);
      point(p);
      text(`${p.x},${p.y}`, p.x + 10, p.y + 10);
    
      const { x, y } = worldToScreen(p);
      resetTransform();
      setFontSize(16);
      text(`${x.toFixed()},${y.toFixed()}`, x - 25, y - 15);
    }
    

    See also: