Loading reference summary…
Canvas
createCanvas(width, height)
Creates the drawing canvas. By default the canvas is transparent - call background() to set a colour. Call this once at the start of your sketch.
| Parameter | Type | Description |
|---|---|---|
| width | int | Canvas width in pixels |
| height | int | Canvas height in pixels |
createCanvas(400, 400) background(30) fill(255, 100, 100) circle(200, 200, 120)
resizeCanvas(width, height)
Resizes an existing canvas.
| Parameter | Type | Description |
|---|---|---|
| width | int | New width in pixels |
| height | int | New height in pixels |
createCanvas(200, 200) background(100) resizeCanvas(400, 300) background(50) circle(200, 150, 80)
background(*args)
Fills the entire canvas with a color or image. Accepts grayscale, RGB, RGBA, a CSS color string, a color object, an array of color components, `background(cssString, alpha)`, `background(colorObject, alpha)`, or `background(image, alpha)`.
| Parameter | Type | Description |
|---|---|---|
| *args | color|image | Grayscale, RGB, RGBA, CSS color string, color object, image, or a list/tuple like [r, g, b, a] |
createCanvas(400, 400)
c = color(30, 30, 80)
background(c, 180)
img = loadImage('https://picsum.photos/400')
background(img, 180)
fill(255)
circle(200, 200, 100)
clear()
Clears the canvas to fully transparent pixels. Unlike `background()`, `clear()` does not paint a color — it erases everything, making the canvas transparent. Useful for layered effects or when the canvas needs to be reset between frames without a background color.
createCanvas(400, 400) background(30, 30, 80) fill(255) circle(200, 200, 120) clear() # Canvas is now transparent fill(255, 100, 100) circle(200, 200, 60)
erase(strengthFill=255, strengthStroke=255)
Switches drawing into erase mode. Shapes drawn after `erase()` punch transparent holes into the canvas instead of painting color. `strengthFill` and `strengthStroke` (0–255) control how strongly fill and stroke erase; 255 is fully transparent, 0 erases nothing. Call `noErase()` to return to normal drawing.
| Parameter | Type | Description |
|---|---|---|
| strengthFill | int | 0–255. How opaque the fill erases (default 255 = fully erase). |
| strengthStroke | int | 0–255. How opaque the stroke erases (default 255 = fully erase). |
createCanvas(400, 400) background(80, 120, 220) fill(255, 180, 0) circle(200, 200, 300) erase() fill(255) circle(200, 200, 140) noErase()
blendMode(mode)
Sets the compositing blend mode for all subsequent drawing. Use the built-in constants to choose a mode. `BLEND` (default) paints normally. Call `blendMode(BLEND)` to reset.
| Parameter | Type | Description |
|---|---|---|
| mode | constant | One of: `BLEND`, `ADD`, `DARKEST`, `LIGHTEST`, `DIFFERENCE`, `EXCLUSION`, `MULTIPLY`, `SCREEN`, `OVERLAY`, `HARD_LIGHT`, `SOFT_LIGHT`, `DODGE`, `BURN`, `REPLACE`, `REMOVE` |
createCanvas(400, 300) background(0) blendMode(ADD) fill(200, 0, 0) circle(160, 150, 180) fill(0, 200, 0) circle(200, 150, 180) fill(0, 0, 200) circle(240, 150, 180) blendMode(BLEND)
smooth() / noSmooth()
Control image smoothing when drawing scaled images. `smooth()` (default) enables bilinear/high-quality interpolation. `noSmooth()` disables it, giving a pixelated look. Note: antialiasing on drawn shapes (lines, circles, etc.) is always on and cannot be disabled in the browser canvas.
createCanvas(400, 300)
img = loadImage('https://picsum.photos/40')
smooth()
image(img, 10, 80, 180, 180)
noSmooth()
image(img, 210, 80, 180, 180)
saveCanvas(filename='canvas', ext='png')
Trigger a browser download of the current canvas as a PNG or JPG file.
| Parameter | Type | Description |
|---|---|---|
| filename | str | Base filename without extension (default 'canvas') |
| ext | str | 'png' (default) or 'jpg' |
createCanvas(400, 300)
background(30, 30, 80)
fill(255, 200, 0)
circle(200, 150, 200)
saveCanvas('my_sketch')
Shapes
rect(x, y, w, h, r1=0)
Draws a rectangle. With mode=CORNER (default), x/y are the top-left corner. Pass a single r for uniform corners, or r1-r4 for individual corners.
| Parameter | Type | Description |
|---|---|---|
| x | float | x position |
| y | float | y position |
| w | float | Width (negative flips the rect) |
| h | float | Height (negative flips the rect) |
| r1 | float | Top-left corner radius (default 0) |
| r2 | float | Top-right corner radius |
| r3 | float | Bottom-right corner radius |
| r4 | float | Bottom-left corner radius |
createCanvas(400, 400) background(220) fill(100, 149, 237) rect(100, 100, 200, 150, 12)
square(x, y, side, r1=0)
Draws a square. Same as rect(x, y, side, side). Supports rounded corners like rect().
| Parameter | Type | Description |
|---|---|---|
| x | float | x position |
| y | float | y position |
| side | float | Side length |
| r1 | float | Corner radius |
createCanvas(400, 400) background(220) fill(100, 149, 237) square(140, 140, 120, 15)
circle(x, y, diameter)
Draws a circle by specifying its centre and diameter.
| Parameter | Type | Description |
|---|---|---|
| x | float | Centre x |
| y | float | Centre y |
| diameter | float | Diameter of the circle |
createCanvas(400, 400) background(220) fill(255, 100, 100) circle(200, 200, 140)
ellipse(x, y, w, h)
Draws an ellipse. By default x/y is the centre.
| Parameter | Type | Description |
|---|---|---|
| x | float | Centre x |
| y | float | Centre y |
| w | float | Width |
| h | float | Height |
createCanvas(400, 400) background(220) fill(180, 120, 220) ellipse(200, 200, 300, 150)
line(x1, y1, x2, y2)
Draws a line between two points.
| Parameter | Type | Description |
|---|---|---|
| x1 | float | Start x |
| y1 | float | Start y |
| x2 | float | End x |
| y2 | float | End y |
createCanvas(400, 400) background(30) stroke(255, 200, 0) strokeWeight(3) line(50, 50, 350, 350)
point(x, y)
Draws a single point. Its size is set by strokeWeight().
| Parameter | Type | Description |
|---|---|---|
| x | float | x position |
| y | float | y position |
createCanvas(400, 400)
background(30)
stroke(255)
strokeWeight(6)
for i in range(20):
point(random(0, 400), random(0, 400))
triangle(x1, y1, x2, y2, x3, y3)
Draws a triangle defined by three vertices.
| Parameter | Type | Description |
|---|---|---|
| x1,y1 | float | First vertex |
| x2,y2 | float | Second vertex |
| x3,y3 | float | Third vertex |
createCanvas(400, 400) background(220) fill(255, 165, 0) triangle(200, 60, 60, 340, 340, 340)
quad(x1, y1, x2, y2, x3, y3, x4, y4)
Draws a quadrilateral defined by four vertices.
| Parameter | Type | Description |
|---|---|---|
| x1,y1 … x4,y4 | float | Four corner vertices in order |
createCanvas(400, 400) background(220) fill(80, 180, 120) quad(100, 200, 200, 80, 320, 160, 280, 320)
arc(x, y, w, h, start, stop, mode=OPEN)
Draws an arc from start to stop using the current angleMode. It follows ellipseMode() for positioning, and mode can be OPEN, CHORD, or PIE.
| Parameter | Type | Description |
|---|---|---|
| x, y | float | Arc position, interpreted according to ellipseMode() |
| w, h | float | Width and height of the bounding ellipse |
| start, stop | float | Start and stop angle |
| mode | const | OPEN, CHORD, or PIE |
createCanvas(400, 400) background(220) fill(255, 80, 80) arc(200, 200, 260, 260, 0, PI * 1.5, PIE)
beginShape(kind=None) / vertex(x, y) / endShape(mode=OPEN)
Begins a custom shape. Call beginShape(), add vertices with vertex() or curve/Bezier vertex functions, then finish with endShape(). Pass CLOSE to close the outer path. Optional kind values include POINTS, LINES, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN, QUADS, and QUAD_STRIP.
| Parameter | Type | Description |
|---|---|---|
| kind | const | Optional primitive mode like TRIANGLES or QUAD_STRIP |
| x, y | float | Vertex coordinates |
| mode | const | OPEN (default) or CLOSE |
createCanvas(400, 400) background(220) fill(100, 160, 240) beginShape() vertex(200, 60) vertex(320, 180) vertex(270, 340) vertex(130, 340) vertex(80, 180) endShape(CLOSE)
endShape(mode=OPEN)
Finishes a shape started with beginShape(). Use CLOSE to connect the final vertex back to the first outer vertex.
| Parameter | Type | Description |
|---|---|---|
| mode | const | OPEN (default) or CLOSE |
createCanvas(400, 220) background(220) noFill() strokeWeight(4) stroke(40) beginShape() vertex(40, 40) vertex(120, 40) vertex(120, 180) endShape() beginShape() vertex(180, 40) vertex(260, 40) vertex(260, 180) endShape(CLOSE)
curveVertex(x, y)
Adds a Catmull-Rom curve vertex inside a beginShape()/endShape() block. Needs at least 4 points; repeat the first and last points if you want the curve to pass through the ends, like p5.js.
| Parameter | Type | Description |
|---|---|---|
| x, y | float | Vertex coordinates |
createCanvas(400, 400) background(220) noFill() stroke(80, 120, 220) strokeWeight(3) beginShape() curveVertex(50, 220) curveVertex(50, 220) curveVertex(120, 120) curveVertex(200, 260) curveVertex(280, 140) curveVertex(350, 220) curveVertex(350, 220) endShape()
curveTightness(amount)
Adjusts how tightly curveVertex() splines bend. `0` matches the default p5.js curve; higher values pull the curve tighter.
| Parameter | Type | Description |
|---|---|---|
| amount | float | Curve tightness amount |
createCanvas(400, 400) background(220) noFill() strokeWeight(3) stroke(70, 90, 220) beginShape() curveVertex(40, 250) curveVertex(40, 250) curveVertex(120, 120) curveVertex(200, 260) curveVertex(280, 140) curveVertex(360, 250) curveVertex(360, 250) endShape() stroke(220, 90, 70) curveTightness(0.8) beginShape() curveVertex(40, 180) curveVertex(40, 180) curveVertex(120, 50) curveVertex(200, 190) curveVertex(280, 70) curveVertex(360, 180) curveVertex(360, 180) endShape()
bezierVertex(cx1, cy1, cx2, cy2, x, y)
Adds a cubic Bezier segment inside a beginShape()/endShape() block. Start the shape with vertex() first.
| Parameter | Type | Description |
|---|---|---|
| cx1, cy1 | float | First control point |
| cx2, cy2 | float | Second control point |
| x, y | float | End point of the segment |
createCanvas(400, 400) background(220) noFill() stroke(220, 80, 80) strokeWeight(3) beginShape() vertex(60, 320) bezierVertex(60, 80, 340, 80, 340, 320) endShape()
quadraticVertex(cx, cy, x, y)
Adds a quadratic curve segment inside a beginShape()/endShape() block. Start the shape with vertex() first.
| Parameter | Type | Description |
|---|---|---|
| cx, cy | float | Control point |
| x, y | float | End point of the segment |
createCanvas(400, 400) background(220) noFill() stroke(80, 170, 120) strokeWeight(3) beginShape() vertex(60, 300) quadraticVertex(200, 60, 340, 300) endShape()
beginContour() / endContour()
Cuts a hole inside a custom filled shape. Call beginContour() and endContour() inside beginShape()/endShape(CLOSE), use vertex() calls for the inner path, and wind the contour in the opposite direction from the outer shape.
createCanvas(400, 400) background(220) fill(90, 140, 240) noStroke() beginShape() vertex(60, 60) vertex(340, 60) vertex(340, 340) vertex(60, 340) beginContour() vertex(140, 140) vertex(140, 260) vertex(260, 260) vertex(260, 140) endContour() endShape(CLOSE)
bezier(x1, y1, cx1, cy1, cx2, cy2, x2, y2)
Draws a cubic Bézier curve.
| Parameter | Type | Description |
|---|---|---|
| x1, y1 | float | Start point |
| cx1, cy1 | float | First control point |
| cx2, cy2 | float | Second control point |
| x2, y2 | float | End point |
createCanvas(400, 400) background(220) noFill() stroke(200, 80, 80) strokeWeight(3) bezier(50, 350, 50, 50, 350, 50, 350, 350)
bezierPoint(a, b, c, d, t)
Returns the coordinate of a point on a cubic Bézier curve at parameter t (0–1). Call once for x, once for y using the matching control-point coordinates.
| Parameter | Type | Description |
|---|---|---|
| a, b, c, d | float | The four x (or y) coordinates of the curve |
| t | float | Position along the curve (0 = start, 1 = end) |
createCanvas(400, 400)
background(220)
noFill()
stroke(200, 80, 80)
strokeWeight(2)
bezier(50, 350, 50, 50, 350, 50, 350, 350)
stroke(50, 200, 100)
strokeWeight(8)
for i in range(11):
t = i / 10
x = bezierPoint(50, 50, 350, 350, t)
y = bezierPoint(350, 50, 50, 350, t)
point(x, y)
bezierTangent(a, b, c, d, t)
Returns the tangent at parameter t along a cubic Bézier curve. Use for x and y separately to get a direction vector.
| Parameter | Type | Description |
|---|---|---|
| a, b, c, d | float | The four x (or y) coordinates of the curve |
| t | float | Position along the curve (0–1) |
createCanvas(400, 400)
background(220)
noFill()
stroke(200,80,80)
strokeWeight(2)
bezier(50,350,50,50,350,50,350,350)
stroke(50,150,240)
strokeWeight(2)
for i in range(6):
t = i / 5
x = bezierPoint(50,50,350,350,t)
y = bezierPoint(350,50,50,350,t)
tx = bezierTangent(50,50,350,350,t)
ty = bezierTangent(350,50,50,350,t)
m = mag(tx,ty)
line(x, y, x + tx/m*30, y + ty/m*30)
curve(x1, y1, x2, y2, x3, y3, x4, y4)
Draws a Catmull-Rom spline through p2 and p3, using p1 and p4 as control handles. curveTightness() adjusts how tightly it follows the points.
| Parameter | Type | Description |
|---|---|---|
| x1, y1 | float | First control point (not drawn through) |
| x2, y2 | float | Start of the visible curve |
| x3, y3 | float | End of the visible curve |
| x4, y4 | float | Last control point (not drawn through) |
createCanvas(400, 400) background(220) noFill() stroke(200,80,80) strokeWeight(3) curve(50,380, 100,100, 300,100, 350,380) curve(100,100, 300,100, 350,380, 400,380)
curvePoint(a, b, c, d, t)
Returns the coordinate of a point on a Catmull-Rom spline at parameter t (0–1). Call separately for x and y.
| Parameter | Type | Description |
|---|---|---|
| a, b, c, d | float | The four x (or y) control-point coordinates |
| t | float | Position along the spline (0–1) |
createCanvas(400, 400)
background(220)
noFill()
stroke(200,80,80)
strokeWeight(2)
curve(50,380,100,100,300,100,350,380)
stroke(50,200,100)
strokeWeight(8)
for i in range(11):
t = i/10
x = curvePoint(50,100,300,350, t)
y = curvePoint(380,100,100,380, t)
point(x, y)
curveTangent(a, b, c, d, t)
Returns the tangent at parameter t along a Catmull-Rom spline. Use for x and y separately to get a direction vector.
| Parameter | Type | Description |
|---|---|---|
| a, b, c, d | float | The four x (or y) control-point coordinates |
| t | float | Position along the spline (0–1) |
createCanvas(400, 400)
background(220)
noFill()
stroke(200,80,80)
strokeWeight(2)
curve(50,380,100,100,300,100,350,380)
stroke(50,150,240)
strokeWeight(2)
for i in range(6):
t = i/5
x = curvePoint(50,100,300,350,t)
y = curvePoint(380,100,100,380,t)
tx = curveTangent(50,100,300,350,t)
ty = curveTangent(380,100,100,380,t)
m = mag(tx,ty)
line(x,y, x+tx/m*30, y+ty/m*30)
Color & Fill
fill(*args)
Sets the fill color for shapes drawn after this call. Accepts grayscale (1 value), RGB (3 values), RGBA (4 values), or a color object.
| Parameter | Type | Description |
|---|---|---|
| *args | color | 1–4 numbers (0–255 in RGB mode) or a color object |
createCanvas(400, 400) background(220) fill(255, 100, 50) circle(130, 200, 100) fill(50, 120, 255) circle(270, 200, 100)
noFill()
Disables fill so shapes are drawn as outlines only.
createCanvas(400, 400) background(220) noFill() stroke(80, 80, 200) strokeWeight(3) circle(200, 200, 160)
stroke(*args)
Sets the stroke (outline) color. Same argument forms as fill().
| Parameter | Type | Description |
|---|---|---|
| *args | color | 1–4 numbers or a color object |
createCanvas(400, 400) background(220) stroke(220, 50, 50) strokeWeight(4) fill(255) rect(100, 100, 200, 200)
noStroke()
Removes the stroke from all shapes drawn after this call.
createCanvas(400, 400) background(220) noStroke() fill(100, 200, 100) rect(80, 80, 240, 240, 20)
strokeWeight(weight)
Sets the thickness of lines and shape outlines in pixels.
| Parameter | Type | Description |
|---|---|---|
| weight | float | Stroke thickness in pixels |
createCanvas(400, 400)
background(220)
for i in range(1, 6):
strokeWeight(i * 2)
line(50, i * 60, 350, i * 60)
strokeCap(cap)
Sets the style for line endings.
| Parameter | Type | Description |
|---|---|---|
| cap | const | ROUND, SQUARE, or PROJECT |
createCanvas(400, 400) background(220) strokeWeight(16) strokeCap(ROUND) line(80, 150, 320, 150) strokeCap(SQUARE) line(80, 220, 320, 220) strokeCap(PROJECT) line(80, 290, 320, 290)
strokeJoin(join)
Sets the style for corners where lines meet.
| Parameter | Type | Description |
|---|---|---|
| join | const | MITER, BEVEL, or ROUND |
createCanvas(400, 400) background(220) strokeWeight(12) noFill() strokeJoin(ROUND) beginShape() vertex(100, 300) vertex(200, 80) vertex(300, 300) endShape()
Color Functions
color(*args)
Creates a reusable color object. Accepts the same arguments as fill().
| Parameter | Type | Description |
|---|---|---|
| *args | color | Grayscale, RGB, RGBA, or HSB/HSL values depending on colorMode |
createCanvas(400, 400) red = color(220, 60, 60) blue = color(60, 100, 220) background(220) fill(red) circle(140, 200, 120) fill(blue) circle(260, 200, 120)
lerpColor(c1, c2, amt)
Interpolates between two colors. amt=0 returns c1, amt=1 returns c2.
| Parameter | Type | Description |
|---|---|---|
| c1 | color | Start color |
| c2 | color | End color |
| amt | float | Amount to interpolate (0.0–1.0) |
createCanvas(400, 80)
c1 = color(255, 50, 50)
c2 = color(50, 100, 255)
for i in range(20):
fill(lerpColor(c1, c2, i / 19))
noStroke()
rect(i * 20, 0, 20, 80)
getPixelColor(x, y)
Returns the color of the canvas pixel at (x, y) as a color object. Equivalent to p5's `get(x, y)` but returns a PyAngelo color rather than a raw `[r,g,b,a]` array, so you can pass the result directly to `fill()`, `stroke()`, `background()`, etc.
| Parameter | Type | Description |
|---|---|---|
| x | int | Pixel x coordinate |
| y | int | Pixel y coordinate |
createCanvas(400, 400) background(255, 100, 50) c = getPixelColor(200, 200) background(30) fill(c) circle(200, 200, 120)
setPixelColor(x, y, *args)
Sets the color of a single canvas pixel at (x, y). Accepts the same color arguments as `fill()` — grayscale, RGB, RGBA, CSS string, or color object. Writes directly to the canvas without needing `loadPixels()`/`updatePixels()`.
| Parameter | Type | Description |
|---|---|---|
| x | int | Pixel x coordinate |
| y | int | Pixel y coordinate |
| *args | color | Color — same formats as fill() |
createCanvas(400, 400)
background(30)
for y in range(400):
for x in range(400):
setPixelColor(x, y, x * 0.64, y * 0.64, 180)
getRegion(x=None, y=None, w=None, h=None)
Captures a rectangular region of the canvas and returns it as an image that can be passed to `image()`. Call with no arguments to capture the entire canvas. Equivalent to p5's `get(x, y, w, h)`.
| Parameter | Type | Description |
|---|---|---|
| x | int|None | Left edge (default: 0) |
| y | int|None | Top edge (default: 0) |
| w | int|None | Width (default: canvas width) |
| h | int|None | Height (default: canvas height) |
createCanvas(400, 400) background(30) fill(255, 100, 100) circle(200, 200, 200) snap = getRegion(100, 100, 200, 200) background(60) image(snap, 100, 100)
loadPixels()
Reads the current canvas into the `pixels` global — a flat RGBA array of integers (0–255). Each pixel at `(x, y)` occupies four consecutive values starting at index `(y * width + x) * 4`. After reading, modify `pixels` freely, then call `updatePixels()` to write the changes back.
createCanvas(400, 400)
background(30)
fill(255, 100, 50)
circle(200, 200, 200)
loadPixels()
for y in range(height):
for x in range(width):
i = (y * width + x) * 4
pixels[i] = 255 - pixels[i] # invert red
updatePixels()
updatePixels()
Writes the `pixels` array back to the canvas after you have modified it. Must be preceded by a `loadPixels()` call.
createCanvas(200, 200)
loadPixels()
for y in range(height):
for x in range(width):
i = (y * width + x) * 4
pixels[i] = x # R
pixels[i+1] = y # G
pixels[i+2] = 100 # B
pixels[i+3] = 255 # A
updatePixels()
filter(kind, param=None)
Applies a visual filter to the entire canvas. `BLUR`, `GRAY`, and `INVERT` use hardware-accelerated CSS filters. `THRESHOLD`, `POSTERIZE`, `OPAQUE`, `ERODE`, and `DILATE` use direct pixel manipulation.
| Parameter | Type | Description |
|---|---|---|
| kind | constant | `BLUR`, `GRAY`, `INVERT`, `OPAQUE`, `THRESHOLD`, `POSTERIZE`, `ERODE`, `DILATE` |
| param | float|None | `BLUR`: radius in pixels (default 3). `THRESHOLD`: level 0.0–1.0 (default 0.5). `POSTERIZE`: colour levels 2–255 (default 4). Others ignore param. |
createCanvas(400, 400)
img = loadImage('https://picsum.photos/400')
image(img, 0, 0)
filter(BLUR, 6)
fill(255)
textSize(28)
textAlign(CENTER, CENTER)
text('Blurred', 200, 200)
colorMode(mode, max1=255, max2=255, max3=255, maxA=255)
Switches between RGB, HSB, and HSL color modes and optionally sets the value range for each channel.
| Parameter | Type | Description |
|---|---|---|
| mode | const | RGB, HSB, or HSL |
| max1–maxA | float | Maximum value for each channel (default 255) |
createCanvas(400, 80)
colorMode(HSB, 360, 100, 100)
for i in range(36):
fill(i * 10, 90, 90)
noStroke()
rect(i * 11, 0, 11, 80)
red(c)
Extracts the red component (0–255) from a color object, CSS string, or any value accepted by color(). Also available as a method: c.red().
| Parameter | Type | Description |
|---|---|---|
| c | color | A color object, CSS string, or numeric value(s) |
c = color(220, 80, 40) print(red(c)) print(green(c)) print(blue(c)) print(alpha(c))
green(c)
Extracts the green component (0–255) from a color object, CSS string, or any value accepted by color(). Also available as a method: c.green().
| Parameter | Type | Description |
|---|---|---|
| c | color | A color object, CSS string, or numeric value(s) |
c = color('#3a9f5b')
print(red(c), green(c), blue(c))
blue(c)
Extracts the blue component (0–255) from a color object, CSS string, or any value accepted by color(). Also available as a method: c.blue().
| Parameter | Type | Description |
|---|---|---|
| c | color | A color object, CSS string, or numeric value(s) |
c = color(0, 0, 200, 128) print(blue(c)) print(alpha(c))
alpha(c)
Extracts the alpha (opacity) component (0–255) from a color object or any value accepted by color(). Also available as a method: c.alpha().
| Parameter | Type | Description |
|---|---|---|
| c | color | A color object, CSS string, or numeric value(s) |
c = color(255, 0, 0, 128) print(alpha(c)) # 128 print(alpha(color(255))) # 255 (fully opaque)
hue(c)
Returns the HSB hue of a color in degrees (0–360). Independent of colorMode.
| Parameter | Type | Description |
|---|---|---|
| c | color | A color object or any value accepted by color() |
print(round(hue(color(255, 0, 0)))) # red → 0 print(round(hue(color(0, 255, 0)))) # green → 120 print(round(hue(color(0, 0, 255)))) # blue → 240
saturation(c)
Returns the HSB saturation (0–100) of a color, or HSL saturation (0–100) when colorMode is HSL.
| Parameter | Type | Description |
|---|---|---|
| c | color | A color object or any value accepted by color() |
print(round(saturation(color(255, 0, 0)))) # 100 (fully saturated) print(round(saturation(color(128, 128, 128)))) # 0 (grey)
brightness(c)
Returns the HSB brightness (0–100) of a color. Independent of colorMode.
| Parameter | Type | Description |
|---|---|---|
| c | color | A color object or any value accepted by color() |
print(round(brightness(color(255, 0, 0)))) # 100 print(round(brightness(color(0, 0, 0)))) # 0 print(round(brightness(color(128, 0, 0)))) # 50
lightness(c)
Returns the HSL lightness (0–100) of a color. Independent of colorMode.
| Parameter | Type | Description |
|---|---|---|
| c | color | A color object or any value accepted by color() |
print(round(lightness(color(255, 0, 0)))) # 50 print(round(lightness(color(255, 255, 255)))) # 100 print(round(lightness(color(0, 0, 0)))) # 0
Text
text(s, x, y, maxWidth=None, maxHeight=None)
Draws text on the canvas at position (x, y). If you pass maxWidth or maxHeight, the text wraps inside that box. If you have not called fill(), text defaults to black like p5.js. Wrapped text is usually easiest to reason about in JAVASCRIPT mode because the box flows downward like normal screen coordinates.
| Parameter | Type | Description |
|---|---|---|
| s | str | The string to draw |
| x, y | float | Position (baseline left by default) |
| maxWidth, maxHeight | float | Optional text box size for wrapping and clipping |
createCanvas(400, 220)
background(30)
textSize(24)
text('PyAngelo text defaults to black until you call fill().', 20, 30, 180, 140)
fill(255)
textAlign(CENTER, CENTER)
text('Wrapped text box', 280, 60, 180, 120)
textSize(size)
Sets the font size for subsequent text() calls.
| Parameter | Type | Description |
|---|---|---|
| size | float | Font size in pixels |
createCanvas(400, 300)
background(220)
fill(30)
for i, s in enumerate([16, 24, 36, 48]):
textSize(s)
text(str(s) + 'px', 20, 40 + i * 60)
textAlign(hAlign, vAlign=BASELINE)
Sets horizontal and vertical text alignment.
| Parameter | Type | Description |
|---|---|---|
| hAlign | const | LEFT, CENTER, or RIGHT |
| vAlign | const | TOP, CENTER, BOTTOM, or BASELINE |
createCanvas(400, 200)
background(220)
fill(30)
textSize(28)
line(200, 0, 200, 200)
textAlign(LEFT)
text('left', 200, 80)
textAlign(RIGHT)
text('right', 200, 130)
loadFont(url, name=None)
Loads a font and registers it with the browser for canvas text. You can load bundled sample fonts such as `/samples/fonts/arcade.ttf`, uploaded sketch assets, or external font URLs. Returns the font family name string, which you can pass directly to `textFont()`. Supports `.ttf`, `.otf`, `.woff`, and `.woff2` files. If `name` is omitted the family name is taken from the filename stem.
| Parameter | Type | Description |
|---|---|---|
| url | str | URL to the font file |
| name | str|None | Optional override for the CSS font-family name |
createCanvas(420, 180)
font = loadFont('/samples/fonts/arcade.ttf')
background(24, 28, 44)
fill(255, 214, 102)
textAlign(CENTER, CENTER)
textFont(font, 30)
text('Arcade!', 210, 90)
textFont(family, size=None)
Sets the font family for subsequent text() calls. An optional size argument also sets the font size at the same time. Pass the return value of `loadFont()` to use a custom web font.
| Parameter | Type | Description |
|---|---|---|
| family | str | A CSS font family name or the string returned by loadFont() |
| size | float | Font size in pixels (optional) |
createCanvas(520, 180)
font = loadFont('https://fonts.gstatic.com/s/monoton/v22/5h1aiZUrOngCibe4TkHLQg.woff2', 'Monoton')
background(16, 12, 28)
fill(110, 231, 255)
textAlign(CENTER, CENTER)
textFont(font, 30)
text('Monoton', 260, 90)
textLeading(leading)
Sets the vertical spacing (line height) between lines of text in text() calls. Defaults to 1.25× the font size.
| Parameter | Type | Description |
|---|---|---|
| leading | float | Pixels between lines |
createCanvas(400, 250)
background(220)
fill(30)
textSize(22)
textLeading(40)
text('Line one
Line two
Line three', 20, 40)
textWrap(mode)
Sets how text is wrapped when `text()` is called with a bounding-box width. `WORD` (default) breaks at spaces between words. `CHAR` breaks at individual characters, useful for non-Latin scripts or tight-fitting layouts.
| Parameter | Type | Description |
|---|---|---|
| mode | constant | `WORD` or `CHAR` |
createCanvas(400, 300)
background(220)
fill(30)
textSize(18)
text('Word wrap: the quick brown fox jumps over the lazy dog', 20, 30, 360, 120)
textWrap(CHAR)
text('Char wrap: the quick brown fox jumps over the lazy dog', 20, 170, 360, 120)
textAscent()
Returns the ascent of the current font — the distance from the baseline to the top of a capital letter.
createCanvas(400, 200)
background(220)
fill(30)
textSize(36)
a = textAscent()
text('Ag', 40, 120)
stroke(200, 50, 50)
noFill()
line(30, 120 - a, 120, 120 - a)
textDescent()
Returns the descent of the current font — the distance from the baseline down to the bottom of descenders like g, p, y.
createCanvas(400, 200)
background(220)
fill(30)
textSize(36)
d = textDescent()
text('Agpy', 40, 100)
stroke(200, 50, 50)
noFill()
line(30, 100 + d, 160, 100 + d)
textStyle(style)
Sets the text style.
| Parameter | Type | Description |
|---|---|---|
| style | const | NORMAL, BOLD, ITALIC, or BOLDITALIC |
createCanvas(400, 200)
background(220)
fill(30)
textSize(30)
textStyle(BOLD)
text('Bold', 20, 70)
textStyle(ITALIC)
text('Italic', 20, 130)
textWidth(s)
Returns the pixel width of a string in the current font settings.
| Parameter | Type | Description |
|---|---|---|
| s | str | The string to measure |
createCanvas(400, 200) background(220) textSize(32) fill(30) msg = 'Hello!' w = textWidth(msg) text(msg, 20, 100) stroke(200, 50, 50) noFill() rect(20, 70, w, 40)
textBounds(s, x=0, y=0)
Return the bounding box of string s drawn at (x, y) using the current text settings. The result has `.x`, `.y`, `.w`, `.h` attributes giving the top-left corner and dimensions. Note: only `WORD` wrap mode is accounted for — `textBounds` measures a single line.
| Parameter | Type | Description |
|---|---|---|
| s | str | The string to measure |
| x | float | x position where text would be drawn (default 0) |
| y | float | y position where text would be drawn (default 0) |
createCanvas(400, 200) background(220) textSize(32) fill(30) msg = 'Hello!' b = textBounds(msg, 20, 100) text(msg, 20, 100) stroke(200, 50, 50) noFill() rect(b.x, b.y, b.w, b.h)
Transforms
translate(x, y)
Moves the coordinate origin by (x, y). Subsequent drawing calls use the new origin.
| Parameter | Type | Description |
|---|---|---|
| x | float | Horizontal translation |
| y | float | Vertical translation |
createCanvas(400, 400) background(220) translate(200, 200) fill(255, 100, 100) rect(-60, -60, 120, 120)
rotate(angle)
Rotates subsequent drawings around the current origin. Angle is in radians unless angleMode(DEGREES) is set.
| Parameter | Type | Description |
|---|---|---|
| angle | float | Rotation angle |
createCanvas(400, 400)
background(220)
translate(200, 200)
for i in range(8):
rotate(PI / 4)
fill(i * 30, 100, 200)
rect(20, -10, 120, 20, 4)
scale(x, y=None)
Scales subsequent drawings. If only x is given, scales uniformly.
| Parameter | Type | Description |
|---|---|---|
| x | float | Horizontal scale factor |
| y | float | Vertical scale factor (defaults to x) |
createCanvas(400, 400)
background(220)
translate(200, 200)
for s in [1.0, 0.7, 0.4]:
scale(s)
noFill()
stroke(80)
rect(-60, -60, 120, 120)
push() / pop()
push() saves the current transform and style state. pop() restores it. Use them together to isolate transform changes.
createCanvas(400, 400) background(220) translate(200, 200) push() rotate(PI / 4) fill(255, 100, 100) rect(-60, -60, 120, 120) pop() fill(100, 100, 255) circle(0, 0, 40)
shearX(angle)
Shears the coordinate system along the X axis by angle. Subsequent shapes will be slanted horizontally. Angle is in radians unless angleMode(DEGREES) is set.
| Parameter | Type | Description |
|---|---|---|
| angle | float | Shear angle |
createCanvas(400, 400) background(220) translate(100, 200) fill(255, 100, 100) rect(0, -60, 120, 120) translate(160, 0) push() shearX(PI / 6) fill(100, 100, 255) rect(0, -60, 120, 120) pop()
shearY(angle)
Shears the coordinate system along the Y axis by angle. Subsequent shapes will be slanted vertically. Angle is in radians unless angleMode(DEGREES) is set.
| Parameter | Type | Description |
|---|---|---|
| angle | float | Shear angle |
createCanvas(400, 400) background(220) translate(200, 80) fill(255, 100, 100) rect(-60, 0, 120, 120) translate(0, 180) push() shearY(PI / 6) fill(100, 100, 255) rect(-60, 0, 120, 120) pop()
applyMatrix(a, b, c, d, e, f)
Multiplies the current transformation matrix by the 2D affine matrix `[a b c d e f]`. Equivalent to the Canvas 2D `transform()` call. Use this for custom transforms not covered by `translate`, `rotate`, or `scale`. Call `push()` / `pop()` to scope the effect.
| Parameter | Type | Description |
|---|---|---|
| a | float | Horizontal scaling |
| b | float | Horizontal skewing |
| c | float | Vertical skewing |
| d | float | Vertical scaling |
| e | float | Horizontal translation |
| f | float | Vertical translation |
createCanvas(400, 400) background(220) fill(100, 100, 255) push() # 45-degree rotation matrix c = cos(PI/4) s = sin(PI/4) applyMatrix(c, s, -s, c, 200, 200) rect(-60, -60, 120, 120) pop()
resetMatrix()
Resets the transformation matrix to its default state, undoing any `translate`, `rotate`, `scale`, `shearX`, `shearY`, or `applyMatrix` calls. Preserves the coordinate mode (CARTESIAN or JAVASCRIPT) and pixel density.
createCanvas(400, 400) background(220) translate(200, 200) fill(255, 100, 100) rect(0, 0, 80, 80) # drawn at 200,200 resetMatrix() fill(100, 100, 255) rect(0, 0, 80, 80) # back at 0,0
Modes
angleMode(mode) / angleMode()
Sets whether angle arguments to rotate(), arc(), and trig functions use RADIANS (default) or DEGREES. Called with no arguments, it returns the current mode.
| Parameter | Type | Description |
|---|---|---|
| mode | const | RADIANS or DEGREES |
createCanvas(400, 400)
background(220)
angleMode(DEGREES)
translate(200, 200)
for d in range(0, 360, 30):
rotate(30)
fill(d, 150, 200)
rect(30, -8, 100, 16, 4)
print(angleMode())
rectMode(mode)
Changes how rect() interprets its x/y arguments.
| Parameter | Type | Description |
|---|---|---|
| mode | const | CORNER (default), CORNERS, CENTER, or RADIUS |
createCanvas(400, 400) background(220) rectMode(CENTER) fill(100, 149, 237) rect(200, 200, 200, 120)
ellipseMode(mode)
Changes how ellipse() and circle() interpret their position arguments.
| Parameter | Type | Description |
|---|---|---|
| mode | const | CENTER (default), CORNER, CORNERS, or RADIUS |
createCanvas(400, 400) background(220) ellipseMode(CORNER) fill(180, 120, 220) ellipse(100, 100, 200, 150)
imageMode(mode)
Changes how image() interprets its x/y arguments.
| Parameter | Type | Description |
|---|---|---|
| mode | const | CORNER (default), CORNERS, CENTER, or RADIUS |
createCanvas(400, 400)
img = loadImage('https://picsum.photos/200')
background(220)
imageMode(CENTER)
image(img, 200, 200, 180, 180)
coordinateMode(mode)
Sets the coordinate system. CARTESIAN (default) has y increasing upward, like standard maths. JAVASCRIPT has y increasing downward, like screen coordinates.
| Parameter | Type | Description |
|---|---|---|
| mode | const | CARTESIAN or JAVASCRIPT |
createCanvas(400, 300) background(40) # Default is CARTESIAN — y increases upward fill(100, 200, 255) circle(100, 50, 40) # appears near bottom # Switch to JAVASCRIPT — y increases downward coordinateMode(JAVASCRIPT) fill(255, 150, 80) circle(300, 50, 40) # appears near top
Images
loadImage(path)
Loads an image from a URL or uploaded asset path.
| Parameter | Type | Description |
|---|---|---|
| path | str | URL or relative path to the image file |
createCanvas(400, 400)
img = loadImage('https://picsum.photos/400')
image(img, 0, 0)
image(img, x, y, w=None, h=None)
Draws an image on the canvas. Omit w/h to use the image's natural size.
| Parameter | Type | Description |
|---|---|---|
| img | image | Image loaded with loadImage() |
| x, y | float | Position (top-left by default, affected by imageMode) |
| w, h | float | Width and height to draw (optional) |
createCanvas(400, 400)
img = loadImage('https://picsum.photos/200')
image(img, 100, 100, 200, 200)
tint(*args)
Tints images drawn after this call with a color. A grayscale value controls brightness; RGB values colorize the image; a fourth value controls transparency. Accepts the same formats as fill().
| Parameter | Type | Description |
|---|---|---|
| *args | float|str | Grayscale, RGB, RGBA, hex string, or CSS color name |
createCanvas(400, 200)
img = loadImage('https://picsum.photos/200/200')
image(img, 0, 0, 200, 200)
tint(255, 80, 80)
image(img, 200, 0, 200, 200)
noTint()
Removes any tint set by tint(). Images drawn after this call are rendered with their original colors.
createCanvas(400, 200)
img = loadImage('https://picsum.photos/200/200')
tint(80, 80, 255)
image(img, 0, 0, 200, 200)
noTint()
image(img, 200, 0, 200, 200)
Audio
Sound once, keep it in a variable, and reuse it throughout your sketch. If the timing matters, call preloadSounds() near the top of your program before your main loop starts. Built-in audio lives under /samples/sounds/ and /samples/music/, while uploaded audio can be loaded with just the filename, such as Sound('jump.wav').
preloadSounds(*paths)
Loads one or more sounds before your sketch needs them. Use this during setup when you want effects or music ready before the first play() call.
| Parameter | Type | Description |
|---|---|---|
| *paths | str | One or more sound URLs or uploaded audio filenames |
preloadSounds('/samples/sounds/blip.wav', '/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
laser = Sound('/samples/sounds/blip.wav')
music = Sound('/samples/music/Myth.mp3')
music.loop(True)
music.volume(0.35)
status = 'Waiting for input'
while True:
background(22, 26, 40)
fill(255)
text('Press 1 for the blip sound, 2 for looping music, SPACE to stop all', width / 2, 70)
text(status, width / 2, 125)
if wasKeyPressed(KEY_1):
laser.stop()
laser.play()
status = 'Played the blip sound'
if wasKeyPressed(KEY_2):
music.play()
status = 'Started the looping music'
if wasKeyPressed(KEY_SPACE):
Sound.stopAll()
status = 'Stopped all sounds'
animate()
Sound(path)
Creates a reusable sound object from a built-in asset, uploaded audio file, or remote URL. For background music, call loop(True) before play().
| Parameter | Type | Description |
|---|---|---|
| path | str | A built-in asset path, uploaded filename, or full URL |
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
music.loop(True)
music.volume(0.4)
music.play()
while True:
background(22, 26, 40)
fill(255)
text('A Sound object can hold looping background music', width / 2, 70)
text('Press SPACE to stop it', width / 2, 125)
if wasKeyPressed(KEY_SPACE):
music.stop()
animate()
play()
Starts the sound. If the sound is paused, play() resumes it from the paused position.
preloadSounds('/samples/sounds/blip.wav')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
laser = Sound('/samples/sounds/blip.wav')
while True:
background(22, 26, 40)
fill(255)
text('Press SPACE to play the sound effect again', width / 2, 70)
text('play() starts or resumes the sound', width / 2, 125)
if wasKeyPressed(KEY_SPACE):
laser.stop()
laser.play()
animate()
pause()
Pauses playback at the current position so a later play() resumes from the same place.
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
music.loop(True)
music.play()
status = 'Playing'
while True:
background(22, 26, 40)
fill(255)
text('Press P to pause or resume the music', width / 2, 70)
text(status, width / 2, 125)
if wasKeyPressed(KEY_P):
if music.isPlaying():
music.pause()
status = 'Paused'
else:
music.play()
status = 'Playing'
animate()
stop()
Stops playback and resets the sound to the beginning.
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
music.play()
status = 'Playing'
while True:
background(22, 26, 40)
fill(255)
text('Press S to stop and rewind. Press P to play again.', width / 2, 70)
text(status, width / 2, 125)
if wasKeyPressed(KEY_S):
music.stop()
status = 'Stopped at the beginning'
if wasKeyPressed(KEY_P):
music.play()
status = 'Playing'
animate()
isPlaying()
Returns True while this Sound instance is actively playing.
preloadSounds('/samples/sounds/blip.wav')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
laser = Sound('/samples/sounds/blip.wav')
while True:
background(22, 26, 40)
fill(255)
text('Press SPACE to play the sound and watch the status', width / 2, 55)
if laser.isPlaying():
fill(120, 220, 160)
circle(width / 2, 140, 70)
fill(20)
text('playing', width / 2, 140)
else:
fill(240, 200, 110)
circle(width / 2, 140, 70)
fill(20)
text('stopped', width / 2, 140)
if wasKeyPressed(KEY_SPACE):
laser.stop()
laser.play()
animate()
seek(position=None)
Without an argument, returns the current playback position in seconds. Pass a number to jump to a specific time.
| Parameter | Type | Description |
|---|---|---|
| position | float|None | Playback position in seconds |
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
music.play()
while True:
background(22, 26, 40)
fill(255)
text('LEFT jumps to 5s, RIGHT jumps to 12.5s, S stops', width / 2, 70)
text('Current position: ' + str(round(music.seek(), 1)) + ' seconds', width / 2, 125)
if wasKeyPressed(KEY_LEFT):
music.seek(5.0)
music.play()
if wasKeyPressed(KEY_RIGHT):
music.seek(12.5)
music.play()
if wasKeyPressed(KEY_S):
music.stop()
animate()
rate(speed=None)
Gets or sets the playback rate. Values above 1.0 play faster; values between 0 and 1.0 play slower.
| Parameter | Type | Description |
|---|---|---|
| speed | float|None | Playback speed multiplier |
preloadSounds('/samples/sounds/blip.wav')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
laser = Sound('/samples/sounds/blip.wav')
current = 1.0
while True:
background(22, 26, 40)
fill(255)
text('Press 1, 2, or 3 to play at different speeds', width / 2, 70)
text('Current rate: ' + str(current), width / 2, 125)
if wasKeyPressed(KEY_1):
current = 0.75
laser.rate(current)
laser.stop()
laser.play()
if wasKeyPressed(KEY_2):
current = 1.0
laser.rate(current)
laser.stop()
laser.play()
if wasKeyPressed(KEY_3):
current = 1.5
laser.rate(current)
laser.stop()
laser.play()
animate()
volume(level=None)
Gets or sets the volume between 0.0 and 1.0.
| Parameter | Type | Description |
|---|---|---|
| level | float|None | Volume from 0.0 (silent) to 1.0 (full) |
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
music.loop(True)
music.play()
while True:
background(22, 26, 40)
fill(255)
text('UP makes it louder, DOWN makes it quieter', width / 2, 70)
text('Volume: ' + str(round(music.volume(), 2)), width / 2, 125)
if wasKeyPressed(KEY_UP):
music.volume(min(1.0, music.volume() + 0.1))
if wasKeyPressed(KEY_DOWN):
music.volume(max(0.0, music.volume() - 0.1))
animate()
loop(state=None)
Gets or sets whether the sound loops. This is especially useful for background music.
| Parameter | Type | Description |
|---|---|---|
| state | bool|None | True to loop, False to stop looping |
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
music.play()
while True:
background(22, 26, 40)
fill(255)
text('Press L to toggle looping. Press P to play.', width / 2, 70)
text('Looping: ' + str(music.loop()), width / 2, 125)
if wasKeyPressed(KEY_L):
music.loop(not music.loop())
if wasKeyPressed(KEY_P):
music.play()
animate()
mute(state=None)
Gets or sets whether this sound is muted.
| Parameter | Type | Description |
|---|---|---|
| state | bool|None | True to mute, False to unmute |
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
music.loop(True)
music.play()
while True:
background(22, 26, 40)
fill(255)
text('Press M to toggle mute while the music keeps playing', width / 2, 70)
text('Muted: ' + str(music.mute()), width / 2, 125)
if wasKeyPressed(KEY_M):
music.mute(not music.mute())
animate()
fade(from_level, to_level, duration_seconds)
Smoothly changes the volume from one level to another over a given number of seconds.
| Parameter | Type | Description |
|---|---|---|
| from_level | float | Starting volume from 0.0 to 1.0 |
| to_level | float | Ending volume from 0.0 to 1.0 |
| duration_seconds | float | Fade time in seconds |
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
music.loop(True)
music.volume(0.3)
music.play()
while True:
background(22, 26, 40)
fill(255)
text('Press U to fade up and D to fade down', width / 2, 70)
text('Current volume: ' + str(round(music.volume(), 2)), width / 2, 125)
if wasKeyPressed(KEY_U):
music.fade(music.volume(), 0.8, 1.5)
if wasKeyPressed(KEY_D):
music.fade(music.volume(), 0.05, 1.5)
animate()
duration()
Returns the total sound length in seconds. For the most reliable value, preload the file first.
preloadSounds('/samples/music/Myth.mp3')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
music = Sound('/samples/music/Myth.mp3')
while True:
background(22, 26, 40)
fill(255)
text('Total duration after preloading', width / 2, 70)
text(str(round(music.duration(), 1)) + ' seconds', width / 2, 125)
animate()
dispose()
Stops this sound and releases its resources. Use this when you are truly finished with a sound object.
preloadSounds('/samples/sounds/blip.wav')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
laser = Sound('/samples/sounds/blip.wav')
disposed = False
while True:
background(22, 26, 40)
fill(255)
text('SPACE plays, X disposes, R recreates the sound object', width / 2, 70)
text('Disposed: ' + str(disposed), width / 2, 125)
if wasKeyPressed(KEY_SPACE) and not disposed:
laser.stop()
laser.play()
if wasKeyPressed(KEY_X) and not disposed:
laser.dispose()
disposed = True
if wasKeyPressed(KEY_R) and disposed:
laser = Sound('/samples/sounds/blip.wav')
disposed = False
animate()
Sound.stopAll()
Stops every active sound in the sketch. Useful when changing scenes or resetting the game.
preloadSounds('/samples/music/Myth.mp3', '/samples/sounds/collision.wav')
createCanvas(520, 240)
textAlign(CENTER, CENTER)
theme = Sound('/samples/music/Myth.mp3')
boom = Sound('/samples/sounds/collision.wav')
theme.loop(True)
status = 'Waiting for input'
while True:
background(22, 26, 40)
fill(255)
text('Press M for music, B for boom, SPACE to stop everything', width / 2, 70)
text(status, width / 2, 125)
if wasKeyPressed(KEY_M):
theme.play()
status = 'Started the music'
if wasKeyPressed(KEY_B):
boom.stop()
boom.play()
status = 'Played the boom effect'
if wasKeyPressed(KEY_SPACE):
Sound.stopAll()
status = 'Stopped all sounds'
animate()
Audio Library
preloadSounds() with that path during setup if the sound needs to be ready immediately.
Sound Effects
blip.wav
/samples/sounds/blip.wav
preloadSounds('/samples/sounds/blip.wav')
sound = Sound('/samples/sounds/blip.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
collision.wav
/samples/sounds/collision.wav
preloadSounds('/samples/sounds/collision.wav')
sound = Sound('/samples/sounds/collision.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
correct.mp3
/samples/sounds/correct.mp3
preloadSounds('/samples/sounds/correct.mp3')
sound = Sound('/samples/sounds/correct.mp3')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
death.wav
/samples/sounds/death.wav
preloadSounds('/samples/sounds/death.wav')
sound = Sound('/samples/sounds/death.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
hit.wav
/samples/sounds/hit.wav
preloadSounds('/samples/sounds/hit.wav')
sound = Sound('/samples/sounds/hit.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
hit2.wav
/samples/sounds/hit2.wav
preloadSounds('/samples/sounds/hit2.wav')
sound = Sound('/samples/sounds/hit2.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
hit3.wav
/samples/sounds/hit3.wav
preloadSounds('/samples/sounds/hit3.wav')
sound = Sound('/samples/sounds/hit3.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
jump.wav
/samples/sounds/jump.wav
preloadSounds('/samples/sounds/jump.wav')
sound = Sound('/samples/sounds/jump.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
pickup.wav
/samples/sounds/pickup.wav
preloadSounds('/samples/sounds/pickup.wav')
sound = Sound('/samples/sounds/pickup.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
powerup.wav
/samples/sounds/powerup.wav
preloadSounds('/samples/sounds/powerup.wav')
sound = Sound('/samples/sounds/powerup.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
powerup2.wav
/samples/sounds/powerup2.wav
preloadSounds('/samples/sounds/powerup2.wav')
sound = Sound('/samples/sounds/powerup2.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
shoot.wav
/samples/sounds/shoot.wav
preloadSounds('/samples/sounds/shoot.wav')
sound = Sound('/samples/sounds/shoot.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
shoot2.wav
/samples/sounds/shoot2.wav
preloadSounds('/samples/sounds/shoot2.wav')
sound = Sound('/samples/sounds/shoot2.wav')
while True:
if wasKeyPressed(KEY_SPACE):
sound.stop()
sound.play()
animate()
Music
Afterburner_01.mp3
/samples/music/Afterburner_01.mp3
preloadSounds('/samples/music/Afterburner_01.mp3')
music = Sound('/samples/music/Afterburner_01.mp3')
music.loop(True)
music.play()
while True:
animate()
Cybernoid_II.mp3
/samples/music/Cybernoid_II.mp3
preloadSounds('/samples/music/Cybernoid_II.mp3')
music = Sound('/samples/music/Cybernoid_II.mp3')
music.loop(True)
music.play()
while True:
animate()
Eliminator_end.mp3
/samples/music/Eliminator_end.mp3
preloadSounds('/samples/music/Eliminator_end.mp3')
music = Sound('/samples/music/Eliminator_end.mp3')
music.loop(True)
music.play()
while True:
animate()
Eliminator_intro.mp3
/samples/music/Eliminator_intro.mp3
preloadSounds('/samples/music/Eliminator_intro.mp3')
music = Sound('/samples/music/Eliminator_intro.mp3')
music.loop(True)
music.play()
while True:
animate()
Golden_Axe.mp3
/samples/music/Golden_Axe.mp3
preloadSounds('/samples/music/Golden_Axe.mp3')
music = Sound('/samples/music/Golden_Axe.mp3')
music.loop(True)
music.play()
while True:
animate()
Golden_Axe_ending.mp3
/samples/music/Golden_Axe_ending.mp3
preloadSounds('/samples/music/Golden_Axe_ending.mp3')
music = Sound('/samples/music/Golden_Axe_ending.mp3')
music.loop(True)
music.play()
while True:
animate()
Golden_Axe_game.mp3
/samples/music/Golden_Axe_game.mp3
preloadSounds('/samples/music/Golden_Axe_game.mp3')
music = Sound('/samples/music/Golden_Axe_game.mp3')
music.loop(True)
music.play()
while True:
animate()
Golden_Axe_selection.mp3
/samples/music/Golden_Axe_selection.mp3
preloadSounds('/samples/music/Golden_Axe_selection.mp3')
music = Sound('/samples/music/Golden_Axe_selection.mp3')
music.loop(True)
music.play()
while True:
animate()
Lemmings_01.mp3
/samples/music/Lemmings_01.mp3
preloadSounds('/samples/music/Lemmings_01.mp3')
music = Sound('/samples/music/Lemmings_01.mp3')
music.loop(True)
music.play()
while True:
animate()
Lemmings_02.mp3
/samples/music/Lemmings_02.mp3
preloadSounds('/samples/music/Lemmings_02.mp3')
music = Sound('/samples/music/Lemmings_02.mp3')
music.loop(True)
music.play()
while True:
animate()
Myth.mp3
/samples/music/Myth.mp3
preloadSounds('/samples/music/Myth.mp3')
music = Sound('/samples/music/Myth.mp3')
music.loop(True)
music.play()
while True:
animate()
PyAngelo.mp3
/samples/music/PyAngelo.mp3
preloadSounds('/samples/music/PyAngelo.mp3')
music = Sound('/samples/music/PyAngelo.mp3')
music.loop(True)
music.play()
while True:
animate()
PyAngeloDance.mp3
/samples/music/PyAngeloDance.mp3
preloadSounds('/samples/music/PyAngeloDance.mp3')
music = Sound('/samples/music/PyAngeloDance.mp3')
music.loop(True)
music.play()
while True:
animate()
RoboCop_3.mp3
/samples/music/RoboCop_3.mp3
preloadSounds('/samples/music/RoboCop_3.mp3')
music = Sound('/samples/music/RoboCop_3.mp3')
music.loop(True)
music.play()
while True:
animate()
SuperMonaco.mp3
/samples/music/SuperMonaco.mp3
preloadSounds('/samples/music/SuperMonaco.mp3')
music = Sound('/samples/music/SuperMonaco.mp3')
music.loop(True)
music.play()
while True:
animate()
Supremacy.mp3
/samples/music/Supremacy.mp3
preloadSounds('/samples/music/Supremacy.mp3')
music = Sound('/samples/music/Supremacy.mp3')
music.loop(True)
music.play()
while True:
animate()
Turbo_Outrun_01.mp3
/samples/music/Turbo_Outrun_01.mp3
preloadSounds('/samples/music/Turbo_Outrun_01.mp3')
music = Sound('/samples/music/Turbo_Outrun_01.mp3')
music.loop(True)
music.play()
while True:
animate()
Turbo_Outrun_02.mp3
/samples/music/Turbo_Outrun_02.mp3
preloadSounds('/samples/music/Turbo_Outrun_02.mp3')
music = Sound('/samples/music/Turbo_Outrun_02.mp3')
music.loop(True)
music.play()
while True:
animate()
Turbo_Outrun_03.mp3
/samples/music/Turbo_Outrun_03.mp3
preloadSounds('/samples/music/Turbo_Outrun_03.mp3')
music = Sound('/samples/music/Turbo_Outrun_03.mp3')
music.loop(True)
music.play()
while True:
animate()
Turbo_Outrun_04.mp3
/samples/music/Turbo_Outrun_04.mp3
preloadSounds('/samples/music/Turbo_Outrun_04.mp3')
music = Sound('/samples/music/Turbo_Outrun_04.mp3')
music.loop(True)
music.play()
while True:
animate()
Turbo_Outrun_ending.mp3
/samples/music/Turbo_Outrun_ending.mp3
preloadSounds('/samples/music/Turbo_Outrun_ending.mp3')
music = Sound('/samples/music/Turbo_Outrun_ending.mp3')
music.loop(True)
music.play()
while True:
animate()
Turbo_Outrun_finish.mp3
/samples/music/Turbo_Outrun_finish.mp3
preloadSounds('/samples/music/Turbo_Outrun_finish.mp3')
music = Sound('/samples/music/Turbo_Outrun_finish.mp3')
music.loop(True)
music.play()
while True:
animate()
Turbo_Outrun_intro.mp3
/samples/music/Turbo_Outrun_intro.mp3
preloadSounds('/samples/music/Turbo_Outrun_intro.mp3')
music = Sound('/samples/music/Turbo_Outrun_intro.mp3')
music.loop(True)
music.play()
while True:
animate()
Turbo_Outrun_us_gold.mp3
/samples/music/Turbo_Outrun_us_gold.mp3
preloadSounds('/samples/music/Turbo_Outrun_us_gold.mp3')
music = Sound('/samples/music/Turbo_Outrun_us_gold.mp3')
music.loop(True)
music.play()
while True:
animate()
success.mp3
/samples/music/success.mp3
preloadSounds('/samples/music/success.mp3')
music = Sound('/samples/music/success.mp3')
music.loop(True)
music.play()
while True:
animate()
we-are-haileybury-8-bit.mp3
/samples/music/we-are-haileybury-8-bit.mp3
preloadSounds('/samples/music/we-are-haileybury-8-bit.mp3')
music = Sound('/samples/music/we-are-haileybury-8-bit.mp3')
music.loop(True)
music.play()
while True:
animate()
Sprite Library
from sprite import *. Sprite angles follow the current angleMode(), sprite colors use the current colorMode() when you set them, and sprites naturally follow the current coordinate system and smoothing mode. The library keeps its own shape, image, and text positioning rules, so changing rectMode(), ellipseMode(), imageMode(), or textAlign() does not make sprite layout unpredictable. Image preloading is auto-awaited just like loadImage() and animate().
from sprite import *
Imports the built-in sprite classes and helpers. The library provides image sprites, text sprites, shape sprites, tweening, and a shared image cache.
from sprite import *
createCanvas(400, 240)
preloadImages('https://picsum.photos/80')
player = Sprite('https://picsum.photos/80', 80, 120)
ball = CircleSprite(220, 120, diameter=48)
ball.setFill(255, 120, 120)
label = TextSprite('Sprite!', 320, 120, fontSize=24)
while True:
background(30)
player.draw()
ball.draw()
label.draw()
animate()
preloadImages(*paths)
Loads one or more images into the sprite cache before you create image sprites. Like loadImage(), this call is auto-awaited by the runtime, so you write it as a normal statement.
| Parameter | Type | Description |
|---|---|---|
| *paths | str | One or more image URLs or uploaded asset paths |
from sprite import *
preloadImages('https://picsum.photos/96', 'https://picsum.photos/80')
hero = Sprite('https://picsum.photos/96', 120, 120)
enemy = Sprite('https://picsum.photos/80', 280, 120)
Sprite(source, x=0, y=0, width=None, height=None)
Creates an image sprite. source can be an image path or an image returned by loadImage(). Sprites use the anchor point as their position; the default anchor is the centre (0.5, 0.5). Shared properties include x, y, width, height, angle, opacity, visible, anchorX, and anchorY. Shared methods include draw(), update(), moveBy(), moveTo(), setSize(), show(), hide(), rotateBy(), rotateTo(), tweenTo(), contains(), containsPoint(), and overlaps().
| Parameter | Type | Description |
|---|---|---|
| source | str|image | An image path or an image object |
| x, y | float | Sprite anchor position |
| width, height | float|None | Optional draw size. Omit to use the image's natural size. |
from sprite import *
preloadImages('https://picsum.photos/120')
player = Sprite('https://picsum.photos/120', 200, 120, width=96)
player.rotateBy(15)
player.opacity = 0.85
player.draw()
TextSprite(text, x=0, y=0, fontSize=16)
Creates a text sprite. Set fontName, fillColor, strokeColor, and strokeWidth after construction, or use setFill(), noFill(), setStroke(), and noStroke(). TextSprite uses the same anchor/position model as the other sprites.
| Parameter | Type | Description |
|---|---|---|
| text | str | Text to draw |
| x, y | float | Sprite anchor position |
| fontSize | float | Initial text size |
from sprite import *
label = TextSprite('Score', 200, 200, fontSize=32)
label.fontName = 'serif'
label.setFill(255, 220, 80)
label.setStroke(40)
label.draw()
RectangleSprite(...) / CircleSprite(...) / EllipseSprite(...)
Creates simple shape-backed sprites. RectangleSprite uses width/height, CircleSprite uses diameter, and EllipseSprite uses width/height. Use setFill(), noFill(), setStroke(), and noStroke() to style them. These classes share the same sprite movement, anchor, tweening, and collision helpers as Sprite and TextSprite.
| Parameter | Type | Description |
|---|---|---|
| RectangleSprite | class | RectangleSprite(x, y, width, height) |
| CircleSprite | class | CircleSprite(x, y, diameter) |
| EllipseSprite | class | EllipseSprite(x, y, width, height) |
from sprite import * box = RectangleSprite(100, 120, 90, 60) box.setFill(80, 160, 255) ball = CircleSprite(220, 120, diameter=48) ball.setFill(255, 120, 120) oval = EllipseSprite(320, 120, 90, 50) oval.setFill(180, 120, 255) box.draw() ball.draw() oval.draw()
Animation & Time
animate(fps=None)
Waits until the next frame should be drawn. Place at the end of your animation loop. Updates deltaTime, frameCount, mouse, and keyboard globals before the next iteration. Runs at the browser's native frame rate (~60 fps) by default. Pass an `fps` value or call `frameRate()` to cap the rate.
| Parameter | Type | Description |
|---|---|---|
| fps | int|None | Target frames per second for this call. Overrides any frameRate() setting for this frame. Defaults to None (use frameRate() target, or uncapped). |
createCanvas(400, 400)
x = 0
while True:
background(30)
fill(255, 200, 50)
circle(x, 200, 40)
x = (x + 3) % 400
animate()
frameRate(fps=None)
Sets the global target frame rate for `animate()`. Call once before your loop and every subsequent `animate()` will throttle to that rate. Call with no argument to get the current actual frame rate (frames per second computed from `deltaTime`).
| Parameter | Type | Description |
|---|---|---|
| fps | int|None | Target frames per second. Pass 0 or None to uncap. Omit to read current actual fps. |
createCanvas(400, 200)
frameRate(10)
while True:
background(30)
fill(255)
textSize(28)
textAlign(CENTER, CENTER)
text('fps: ' + str(round(frameRate(), 1)), 200, 100)
animate()
sleep(seconds)
Pauses execution for the given number of seconds.
| Parameter | Type | Description |
|---|---|---|
| seconds | float | Time to wait in seconds |
createCanvas(400, 200)
for c in [(255,80,80), (80,255,80), (80,80,255)]:
background(*c)
sleep(0.8)
millis()
Returns the number of milliseconds elapsed since the sketch started.
createCanvas(400, 200)
while True:
background(30)
fill(255)
textSize(36)
textAlign(CENTER, CENTER)
text(str(millis() // 1000) + 's', 200, 100)
animate()
frameCount (global variable)
The number of frames that have been drawn since the sketch started. Incremented each time animate() is called.
createCanvas(400, 200)
while True:
background(30)
fill(255)
textSize(32)
textAlign(CENTER, CENTER)
text('Frame ' + str(frameCount), 200, 100)
animate()
deltaTime (global variable)
Milliseconds elapsed since the previous frame. Updated by animate(). At 60 fps this is roughly 16. Multiply by a small factor to get frame-rate-independent movement (e.g. deltaTime * 0.2 moves about 3 pixels per frame at 60 fps).
createCanvas(400, 400)
speed = 0.2 # pixels per millisecond
x = 0
while True:
background(30)
x += deltaTime * speed
fill(100, 200, 255)
circle(x % 400, 200, 40)
animate()
day() / month() / year()
Return the current day (1–31), month (1–12), or year as integers from the system clock.
createCanvas(400, 200) background(30) fill(255) textSize(28) textAlign(CENTER, CENTER) text(str(day()) + '/' + str(month()) + '/' + str(year()), 200, 100)
hour() / minute() / second()
Return the current hour (0–23), minute (0–59), or second (0–59) from the system clock.
createCanvas(400, 200)
while True:
background(30)
fill(255)
textSize(36)
textAlign(CENTER, CENTER)
text(str(hour()) + ':' + str(minute()).zfill(2) + ':' + str(second()).zfill(2), 200, 100)
animate()
Mouse Input
mouseX, mouseY (global variables)
Current mouse position on the canvas in pixels. Updated when animate() or sleep() is called. Between those calls the value stays frozen.
createCanvas(400, 400)
while True:
background(30)
fill(255, 150, 50)
circle(mouseX, mouseY, 40)
animate()
pmouseX, pmouseY (global variables)
Mouse position from the previous frame. Updated by animate(). Useful for drawing lines that follow mouse movement.
createCanvas(400, 400)
background(30)
while True:
if mouseIsPressed:
stroke(255, 100, 100)
strokeWeight(3)
line(pmouseX, pmouseY, mouseX, mouseY)
animate()
movedX, movedY (global variables)
How far the mouse moved since the last frame (in pixels). Updated by `animate()`. Equivalent to `mouseX - pmouseX` and `mouseY - pmouseY`.
createCanvas(400, 400)
while True:
background(30)
speed = sqrt(movedX**2 + movedY**2)
fill(min(255, speed * 8), 100, 200)
circle(mouseX, mouseY, max(10, speed * 3))
animate()
mouseIsPressed (global variable)
True while any mouse button is held down. Updated when animate() or sleep() is called.
createCanvas(400, 400)
while True:
if mouseIsPressed:
background(80, 30, 30)
fill(255, 100, 100)
else:
background(30)
fill(200)
circle(200, 200, 120)
animate()
mouseButton (global variable)
The mouse button currently pressed: LEFT, RIGHT, or CENTER. Updated when animate() or sleep() is called.
createCanvas(400, 200)
while True:
background(30)
fill(255)
textAlign(CENTER, CENTER)
textSize(24)
btn = str(mouseButton) if mouseIsPressed else 'none'
text('Button: ' + btn, 200, 100)
animate()
focused (global variable)
True if the browser window currently has keyboard focus. Updated by `animate()`. Useful for pausing a sketch when the user switches away.
createCanvas(400, 200)
while True:
background(30 if focused else 60)
fill(255)
textAlign(CENTER, CENTER)
textSize(28)
text('Focused' if focused else 'Click to focus', 200, 100)
animate()
windowWidth, windowHeight (global variables)
The current browser window dimensions in CSS pixels. Updated by `animate()`. Useful for full-window responsive sketches.
createCanvas(400, 200)
while True:
background(30)
fill(255)
textAlign(CENTER, CENTER)
textSize(20)
text(str(windowWidth) + ' x ' + str(windowHeight), 200, 100)
animate()
displayWidth, displayHeight (global variables)
The physical screen resolution in pixels (`screen.width` / `screen.height`). Unlike `windowWidth`/`windowHeight` these do not change when the browser is resized.
createCanvas(400, 200)
background(30)
fill(255)
textAlign(CENTER, CENTER)
textSize(20)
text('Screen: ' + str(displayWidth) + 'x' + str(displayHeight), 200, 100)
Keyboard Input
keyIsPressed (global variable)
True while any key is held down. Updated when animate() or sleep() is called.
createCanvas(400, 200)
while True:
background(30)
fill(255)
textAlign(CENTER, CENTER)
textSize(28)
text('Hold a key!' if not keyIsPressed else key, 200, 100)
animate()
key (global variable)
The string value of the last key pressed (e.g. 'a', 'Enter', ' '). Updated when animate() or sleep() is called.
createCanvas(400, 200)
while True:
background(30)
fill(255)
textAlign(CENTER, CENTER)
textSize(48)
text(key, 200, 100)
animate()
keyIsDown(code)
Returns True if the given key is currently held. Use KEY_* constants.
| Parameter | Type | Description |
|---|---|---|
| code | const | A KEY_* constant such as KEY_LEFT, KEY_SPACE, KEY_A |
createCanvas(400, 400)
x, y = 200, 200
while True:
background(30)
if keyIsDown(KEY_LEFT): x -= 3
if keyIsDown(KEY_RIGHT): x += 3
if keyIsDown(KEY_UP): y -= 3
if keyIsDown(KEY_DOWN): y += 3
fill(100, 200, 255)
circle(x, y, 40)
animate()
wasKeyPressed(code)
Returns True once per keypress — the event is consumed so repeated calls in the same frame return False. Useful for discrete actions like jumping.
| Parameter | Type | Description |
|---|---|---|
| code | const | A KEY_* constant |
createCanvas(400, 400)
count = 0
while True:
if wasKeyPressed(KEY_SPACE):
count += 1
background(30)
fill(255)
textAlign(CENTER, CENTER)
textSize(36)
text('Jumps: ' + str(count), 200, 200)
animate()
Console I/O
print(*args, sep=' ', end='\n')
Prints values to the console. Works like Python's built-in print().
| Parameter | Type | Description |
|---|---|---|
| *args | any | Values to print |
| sep | str | Separator between values (default space) |
| end | str | String appended after the last value (default newline) |
print('Hello, PyAngelo!')
for i in range(1, 6):
print('Line', i)
input(prompt='')
Displays a prompt and waits for the user to type a line.
| Parameter | Type | Description |
|---|---|---|
| prompt | str | Text shown to the user before the input field |
name = input('What is your name? ')
print('Hello,', name + '!')
consoleClear(*args)
Clears all output from the console. Optionally sets a background color using the same arguments as fill(); omit to restore the default background.
| Parameter | Type | Description |
|---|---|---|
| *args | color | Optional — same arguments as fill() |
for i in range(10):
print('Line', i)
sleep(1)
consoleClear()
print('Cleared!')
consoleColor(*args)
Changes the color of text printed to the console after this call.
| Parameter | Type | Description |
|---|---|---|
| *args | color | Same arguments as fill() |
consoleColor(255, 100, 100)
print('Red text')
consoleColor(100, 255, 100)
print('Green text')
consoleColor(100, 150, 255)
print('Blue text')
consoleTextSize(size)
Sets the console font size in pixels for existing and future output, including input prompts.
| Parameter | Type | Description |
|---|---|---|
| size | number | Font size in pixels |
consoleTextSize(24)
print('Large text')
consoleTextSize(12)
print('Small text')
consoleHighlight(*args)
Changes the background (highlight) color of subsequent console output.
| Parameter | Type | Description |
|---|---|---|
| *args | color | Same arguments as fill() |
consoleHighlight(50, 50, 120)
print('Highlighted!')
consoleHighlight(0)
print('Normal')
Cloud Variables
cloudGet(name, default=0)
Reads a cloud variable from the current sketch. If the variable does not exist yet, returns `default` instead. `cloudGet()` returns an `int` for whole-number values and a `float` for decimal values.
| Parameter | Type | Description |
|---|---|---|
| name | str | Cloud variable name. Use letters, digits, and underscores, starting with a letter. |
| default | number | Fallback value returned when the variable does not exist yet (default 0). |
createCanvas(420, 220)
textAlign(CENTER, CENTER)
while True:
if wasKeyPressed(KEY_SPACE):
cloudChange('visits', 1)
visits = cloudGet('visits', 0)
background(24, 28, 44)
fill(255)
textSize(24)
text('Shared visits: ' + str(visits), width / 2, 85)
textSize(16)
text('Press SPACE to add one in every tab running this saved sketch', width / 2, 140)
animate()
cloudSet(name, value)
Stores a numeric value in a cloud variable for the current sketch. Use this when you want to replace the current value completely. In public sketches, other logged-in users running the same sketch will see the update shortly after it syncs.
| Parameter | Type | Description |
|---|---|---|
| name | str | Cloud variable name. |
| value | number | New numeric value to store. |
createCanvas(420, 220)
textAlign(CENTER, CENTER)
value = cloudGet('shared_value', 0)
while True:
background(24, 28, 44)
fill(255)
textSize(24)
text('Shared value: ' + str(value), width / 2, 75)
textSize(16)
text('Press 1, 2, or 3 to replace it for everyone', width / 2, 125)
if wasKeyPressed(KEY_1):
cloudSet('shared_value', 1)
if wasKeyPressed(KEY_2):
cloudSet('shared_value', 2)
if wasKeyPressed(KEY_3):
cloudSet('shared_value', 3)
value = cloudGet('shared_value', 0)
animate()
cloudChange(name, delta=1)
Atomically adds `delta` to a cloud variable and returns the new value. This is the best way to build shared counters and leaderboards because two users incrementing at the same time will not overwrite each other.
| Parameter | Type | Description |
|---|---|---|
| name | str | Cloud variable name. |
| delta | number | Amount to add. Can be positive or negative (default 1). |
createCanvas(420, 220)
textAlign(CENTER, CENTER)
score = cloudGet('score', 0)
while True:
background(24, 28, 44)
fill(255)
textSize(24)
text('Shared score: ' + str(score), width / 2, 80)
textSize(16)
text('Press SPACE to add 1 for everyone running this sketch', width / 2, 135)
if wasKeyPressed(KEY_SPACE):
score = cloudChange('score', 1)
else:
score = cloudGet('score', 0)
animate()
Vector
Vector(x=0, y=0, z=0)
A 2D or 3D vector. Operators (+, -, *, /) return new Vectors. Methods (.add, .sub, .mult, .div, .normalize, .limit, .setMag, .rotate, .lerp) mutate in place and return self so they can be chained. abs(v) returns the magnitude; len(v) is always 3.
| Parameter | Type | Description |
|---|---|---|
| x | float | x component (default 0) |
| y | float | y component (default 0) |
| z | float | z component (default 0) |
v = Vector(3, 4) print(v) # Vector(3.0, 4.0, 0.0) print(abs(v)) # 5.0 (magnitude) print(v * 2) # Vector(6.0, 8.0, 0.0) (new vector) v.mult(0.5) # mutate in place print(v) # Vector(1.5, 2.0, 0.0)
createVector(x=0, y=0, z=0)
p5.js-compatible alias for Vector(x, y, z). Prefer Vector() directly in new code.
| Parameter | Type | Description |
|---|---|---|
| x | float | x component |
| y | float | y component |
| z | float | z component (default 0) |
v = createVector(1, 2) print(v) # Vector(1.0, 2.0, 0.0)
Vector.fromAngle(angle, length=1)
Create a 2D unit vector pointing in the given direction. Respects angleMode().
| Parameter | Type | Description |
|---|---|---|
| angle | float | Direction angle in the current angleMode |
| length | float | Magnitude of the resulting vector (default 1) |
v = Vector.fromAngle(0) print(v) # Vector(1.0, 0.0, 0.0) angleMode(DEGREES) v = Vector.fromAngle(90) print(round(v.x, 5), round(v.y, 5))
Vector.random2D()
Return a random 2D unit vector with a uniformly distributed direction.
v = Vector.random2D() print(round(abs(v), 5)) # always 1.0
Vector.random3D()
Return a random 3D unit vector uniformly distributed on the unit sphere.
v = Vector.random3D() print(round(abs(v), 5)) # always 1.0
v.mag() | abs(v)
Return the magnitude (length) of the vector. abs(v) is a Pythonic shorthand that does the same thing.
v = Vector(3, 4) print(v.mag()) # 5.0 print(abs(v)) # 5.0
v.magSq()
Return the squared magnitude. Faster than mag() when you only need to compare lengths.
v = Vector(3, 4) print(v.magSq()) # 25.0
v.copy()
Return a new Vector with the same x, y, z components.
v1 = Vector(1, 2, 3) v2 = v1.copy() v2.x = 99 print(v1) # Vector(1.0, 2.0, 3.0) — unchanged
v.add(other) | v + other
Add another vector (or scalar) to this one. The method mutates v and returns self for chaining. The + operator returns a new Vector and leaves v unchanged.
| Parameter | Type | Description |
|---|---|---|
| other | Vector | float | Vector or scalar to add |
v = Vector(1, 2) v.add(Vector(3, 4)) # mutates v → (4, 6) print(v) w = v + Vector(1, 1) # new vector → (5, 7) print(w) print(v) # v is still (4, 6)
v.sub(other) | v - other
Subtract another vector (or scalar). The method mutates v; the - operator returns a new Vector.
| Parameter | Type | Description |
|---|---|---|
| other | Vector | float | Vector or scalar to subtract |
v = Vector(5, 7) v.sub(Vector(2, 3)) print(v) # Vector(3.0, 4.0, 0.0)
v.mult(scalar) | v * scalar
Multiply by a scalar. The method mutates v; the * operator returns a new Vector.
| Parameter | Type | Description |
|---|---|---|
| scalar | float | Scale factor |
v = Vector(3, 4) print(v * 2) # Vector(6.0, 8.0, 0.0) — new v.mult(2) print(v) # Vector(6.0, 8.0, 0.0) — mutated
v.div(scalar) | v / scalar
Divide by a scalar. The method mutates v; the / operator returns a new Vector.
| Parameter | Type | Description |
|---|---|---|
| scalar | float | Divisor |
v = Vector(6, 8) print(v / 2) # Vector(3.0, 4.0, 0.0) — new v.div(2) print(v) # Vector(3.0, 4.0, 0.0) — mutated
v.normalize()
Scale this vector to unit length (magnitude 1). Mutates in place. No-op on the zero vector.
v = Vector(3, 4) v.normalize() print(round(abs(v), 5)) # 1.0 print(v.x, v.y) # 0.6 0.8
v.limit(max)
If the magnitude exceeds max, scale down to max. Otherwise leave unchanged. Mutates in place.
| Parameter | Type | Description |
|---|---|---|
| max | float | Maximum allowed magnitude |
v = Vector(3, 4) # magnitude 5 v.limit(3) print(round(abs(v), 5)) # 3.0
v.setMag(mag)
Set the magnitude to the given value, keeping the same direction. Mutates in place.
| Parameter | Type | Description |
|---|---|---|
| mag | float | Desired magnitude |
v = Vector(3, 4) v.setMag(10) print(round(abs(v), 5)) # 10.0
v.dot(other)
Return the dot product of this vector and another.
| Parameter | Type | Description |
|---|---|---|
| other | Vector | The other vector |
a = Vector(1, 0) b = Vector(0, 1) print(a.dot(b)) # 0.0 (perpendicular) print(a.dot(a)) # 1.0
v.cross(other)
Return the cross product as a new Vector. For 2D vectors the result is a vector along the Z axis.
| Parameter | Type | Description |
|---|---|---|
| other | Vector | The other vector |
a = Vector(1, 0, 0) b = Vector(0, 1, 0) print(a.cross(b)) # Vector(0.0, 0.0, 1.0)
v.dist(other)
Return the Euclidean distance between this vector and another.
| Parameter | Type | Description |
|---|---|---|
| other | Vector | The other vector |
a = Vector(0, 0) b = Vector(3, 4) print(a.dist(b)) # 5.0
v.lerp(other, t)
Linearly interpolate this vector toward other by t (0 = no movement, 1 = jump to other). Mutates in place.
| Parameter | Type | Description |
|---|---|---|
| other | Vector | Target vector |
| t | float | Interpolation amount 0–1 |
v = Vector(0, 0) v.lerp(Vector(10, 20), 0.5) print(v) # Vector(5.0, 10.0, 0.0)
v.heading()
Return the 2D direction angle of this vector in the current angleMode().
v = Vector(1, 0) print(v.heading()) # 0.0 v = Vector(0, 1) print(round(v.heading(), 5)) # ~1.5708 (PI/2 in RADIANS)
v.rotate(angle)
Rotate this 2D vector by the given angle (respects angleMode). Mutates in place.
| Parameter | Type | Description |
|---|---|---|
| angle | float | Rotation angle in the current angleMode |
v = Vector(1, 0) v.rotate(PI/2) print(round(v.x, 5), round(v.y, 5)) # 0.0 1.0
v.angleBetween(other)
Return the angle between this vector and another in the current angleMode().
| Parameter | Type | Description |
|---|---|---|
| other | Vector | The other vector |
a = Vector(1, 0) b = Vector(0, 1) print(round(a.angleBetween(b), 5)) # ~1.5708 (PI/2)
v.array()
Return the components as a [x, y, z] list.
v = Vector(1, 2, 3) print(v.array()) # [1.0, 2.0, 3.0] print(list(v)) # same via iteration
v.set(x=0, y=0, z=0)
Set the components of this vector in place. Accepts a Vector, a list/tuple, or individual x, y, z values. Returns self.
| Parameter | Type | Description |
|---|---|---|
| x | Vector | list | float | A Vector, [x,y,z] list, or numeric x component |
| y | float | y component (ignored if x is a Vector or list) |
| z | float | z component (ignored if x is a Vector or list) |
v = Vector(1, 2, 3) v.set(10, 20) print(v) # Vector(10.0, 20.0, 0.0) v.set(Vector(5, 6, 7)) print(v) # Vector(5.0, 6.0, 7.0)
v.setHeading(angle)
Set the 2D direction of this vector to angle (respects angleMode) while keeping the same magnitude. Mutates in place.
| Parameter | Type | Description |
|---|---|---|
| angle | float | New heading angle in the current angleMode |
v = Vector(3, 4) # mag=5, heading=~53° v.setHeading(0) print(round(v.x, 5), round(v.y, 5)) # 5.0 0.0
v.reflect(normal)
Reflect this vector off a surface described by the given normal vector. The normal is automatically normalised. Mutates in place.
| Parameter | Type | Description |
|---|---|---|
| normal | Vector | Surface normal (does not need to be unit length) |
vel = Vector(1, -1) # moving down-right norm = Vector(0, 1) # floor normal vel.reflect(norm) print(vel) # Vector(1.0, 1.0, 0.0) — bounced up
v.rem(other)
Return a new Vector with component-wise modulo (x%other, y%other, z%other).
| Parameter | Type | Description |
|---|---|---|
| other | Vector | float | Divisor — a Vector or scalar |
v = Vector(7, 5, 9) print(v.rem(3)) # Vector(1.0, 2.0, 0.0) print(v.rem(Vector(3, 4, 5))) # Vector(1.0, 1.0, 4.0)
v.slerp(other, t)
Spherical linear interpolation from this vector to other by t (0–1). Unlike lerp(), slerp() keeps the interpolated vector on the same arc, smoothly rotating between the two directions. Returns a new Vector.
| Parameter | Type | Description |
|---|---|---|
| other | Vector | Target vector |
| t | float | Interpolation amount 0–1 |
a = Vector(1, 0) b = Vector(0, 1) m = a.slerp(b, 0.5) print(round(abs(m), 5)) # 1.0 — constant magnitude print(round(m.heading(), 4)) # ~0.7854 (PI/4)
Vector.fromAngles(theta, phi, length=1)
Create a 3D vector from spherical coordinates (respects angleMode). theta is the polar angle from the +Z axis; phi is the azimuthal angle in the XY plane.
| Parameter | Type | Description |
|---|---|---|
| theta | float | Polar angle from +Z axis |
| phi | float | Azimuthal angle in XY plane |
| length | float | Magnitude of the result (default 1) |
v = Vector.fromAngles(PI/2, 0) print(round(v.x,5), round(v.y,5), round(v.z,5)) # 1.0 0.0 0.0
Math & Utility
acos(value)
Returns the arc cosine of a value. Results use the current angleMode(). Invalid input returns NaN.
| Parameter | Type | Description |
|---|---|---|
| value | float | A value usually in the range -1 to 1 |
print(acos(1)) print(acos(0)) angleMode(DEGREES) print(acos(0)) print(acos(2))
asin(value)
Returns the arc sine of a value in the current angleMode(). Invalid input returns NaN.
| Parameter | Type | Description |
|---|---|---|
| value | float | A value usually in the range -1 to 1 |
print(asin(0)) print(round(asin(0.5), 3)) angleMode(DEGREES) print(asin(0.5)) print(asin(2))
atan(value)
Returns the arc tangent of a value in the current angleMode(). Invalid input returns NaN.
| Parameter | Type | Description |
|---|---|---|
| value | float | The tangent ratio to convert to an angle |
print(round(atan(1), 3))
angleMode(DEGREES)
print(atan(1))
print(atan('bad'))
atan2(y, x)
Returns the angle from the origin to the point (x, y), using the current angleMode(). Invalid input returns NaN.
| Parameter | Type | Description |
|---|---|---|
| y | float | Vertical offset from the origin |
| x | float | Horizontal offset from the origin |
print(round(atan2(1, 1), 3))
angleMode(DEGREES)
print(atan2(1, 0))
print(atan2('bad', 1))
cos(angle)
Returns the cosine of an angle. The input angle uses the current angleMode().
| Parameter | Type | Description |
|---|---|---|
| angle | float | The angle to evaluate |
createCanvas(400, 200)
while True:
background(30)
x = 200 + cos(frameCount * 0.05) * 120
fill(255)
circle(x, 100, 30)
animate()
degrees(radians)
Converts an angle from radians to degrees.
| Parameter | Type | Description |
|---|---|---|
| radians | float | Angle measured in radians |
print(degrees(PI)) print(degrees(HALF_PI))
dist(x1, y1, x2, y2)
Returns the Euclidean distance between two points.
| Parameter | Type | Description |
|---|---|---|
| x1,y1 | float | First point |
| x2,y2 | float | Second point |
createCanvas(400, 400)
while True:
background(30)
d = dist(mouseX, mouseY, 200, 200)
fill(255)
textAlign(CENTER, CENTER)
textSize(24)
text('dist: ' + str(round(d)), 200, 200)
animate()
lerp(start, stop, amt)
Linear interpolation between start and stop. amt=0 returns start, amt=1 returns stop.
| Parameter | Type | Description |
|---|---|---|
| start | float | Start value |
| stop | float | End value |
| amt | float | Interpolation amount (0.0–1.0) |
createCanvas(400, 400)
x = 0
while True:
x = lerp(x, mouseX, 0.1)
background(30)
fill(255, 200, 50)
circle(x, 200, 40)
animate()
constrain(n, low, high)
Clamps n to the range [low, high].
| Parameter | Type | Description |
|---|---|---|
| n | float | Value to constrain |
| low | float | Minimum allowed value |
| high | float | Maximum allowed value |
createCanvas(400, 400)
while True:
background(30)
x = constrain(mouseX, 100, 300)
fill(100, 200, 255)
circle(x, 200, 50)
animate()
map(value, start1, stop1, start2, stop2, withinBounds=False)
Re-maps a number from one range to another. When withinBounds is True the result is clamped to the output range.
| Parameter | Type | Description |
|---|---|---|
| value | float | The value to re-map |
| start1, stop1 | float | Input range |
| start2, stop2 | float | Output range |
| withinBounds | bool | If True, clamp result to output range (default False) |
createCanvas(400, 400)
while True:
background(30)
r = map(mouseX, 0, 400, 0, 255)
b = map(mouseY, 0, 400, 0, 255)
fill(r, 100, b)
circle(200, 200, 160)
animate()
random(low_or_list=1, high=None)
Returns a random float in [0, low) when called with one number, in [low, high) with two numbers, or a random element when passed a list.
| Parameter | Type | Description |
|---|---|---|
| low_or_list | float|list | Upper bound, or a list to choose from |
| high | float | Upper bound (optional) |
createCanvas(400, 400)
background(220)
for _ in range(60):
fill(random(255), random(255), random(255), 180)
noStroke()
circle(random(400), random(400), random(20, 60))
randomSeed(seed)
Seeds the random number generator so that subsequent random() and randomGaussian() calls produce a reproducible sequence.
| Parameter | Type | Description |
|---|---|---|
| seed | int | Integer seed value |
createCanvas(400, 400)
randomSeed(42)
background(220)
for _ in range(40):
fill(random(255), random(255), random(255), 180)
noStroke()
circle(random(400), random(400), random(20, 60))
randomGaussian(mean=0, sd=1)
Returns a random number drawn from a Gaussian (normal) distribution with the given mean and standard deviation.
| Parameter | Type | Description |
|---|---|---|
| mean | float | Centre of the distribution (default 0) |
| sd | float | Standard deviation (default 1) |
createCanvas(400, 300)
background(220)
noStroke()
for _ in range(500):
x = randomGaussian(200, 50)
y = randomGaussian(150, 40)
fill(80, 120, 220, 80)
circle(x, y, 8)
noise(x, y=0, z=0)
Returns a Perlin noise value in [0, 1] for the given coordinates. Nearby inputs return similar values, producing smooth variation.
| Parameter | Type | Description |
|---|---|---|
| x | float | First noise coordinate |
| y | float | Second coordinate (optional) |
| z | float | Third coordinate (optional) |
createCanvas(400, 200)
t = 0
while True:
background(30)
noFill()
stroke(100, 200, 255)
strokeWeight(2)
beginShape()
for x in range(0, 401, 5):
y = noise(x * 0.01, t) * 180 + 10
vertex(x, y)
endShape()
t += 0.02
animate()
noiseSeed(seed)
Seeds the Perlin noise generator for reproducible results.
| Parameter | Type | Description |
|---|---|---|
| seed | int | Integer seed value |
createCanvas(400, 200)
noiseSeed(42)
background(30)
noFill()
stroke(100, 200, 255)
strokeWeight(2)
beginShape()
for x in range(401):
y = noise(x * 0.01) * 180 + 10
vertex(x, y)
endShape()
noiseDetail(lod, falloff)
Adjusts the character of Perlin noise. lod is the number of octaves; falloff controls how much each octave contributes.
| Parameter | Type | Description |
|---|---|---|
| lod | int | Number of noise octaves (higher = more detail) |
| falloff | float | Amplitude falloff per octave (0.0–1.0) |
createCanvas(400, 200)
noiseDetail(8, 0.5)
background(30)
noFill()
stroke(255, 180, 50)
strokeWeight(2)
beginShape()
for x in range(401):
y = noise(x * 0.005) * 180 + 10
vertex(x, y)
endShape()
mag(x, y)
Returns the magnitude of a 2D vector.
| Parameter | Type | Description |
|---|---|---|
| x | float | Horizontal component |
| y | float | Vertical component |
print(mag(3, 4)) print(round(mag(5, 12), 2))
norm(value, low, high)
Normalizes a value from the range [low, high] into the range 0 to 1.
| Parameter | Type | Description |
|---|---|---|
| value | float | The value to normalize |
| low | float | Lower bound of the input range |
| high | float | Upper bound of the input range |
print(norm(25, 0, 100)) print(norm(75, 0, 100))
nf(n, left=0, right=0)
Formats a number as a string, padding the integer part with leading zeros and optionally fixing decimal places.
| Parameter | Type | Description |
|---|---|---|
| n | float | The number to format |
| left | int | Minimum digits before the decimal (zero-padded) |
| right | int | Digits after the decimal point |
print(nf(42, 5)) print(nf(3.14159, 1, 2)) print(nf(-7, 3))
nfc(n, right=0)
Formats a number as a string with comma separators for thousands groups.
| Parameter | Type | Description |
|---|---|---|
| n | float | The number to format |
| right | int | Digits after the decimal point |
print(nfc(1234567)) print(nfc(9999.5, 2))
nfp(n, left=0, right=0)
Like nf() but always includes a leading + or - sign.
| Parameter | Type | Description |
|---|---|---|
| n | float | The number to format |
| left | int | Minimum digits before the decimal |
| right | int | Digits after the decimal point |
print(nfp(42, 3)) print(nfp(-7, 3))
nfs(n, left=0, right=0)
Like nf() but adds a leading space for positive numbers so they align with negative ones.
| Parameter | Type | Description |
|---|---|---|
| n | float | The number to format |
| left | int | Minimum digits before the decimal |
| right | int | Digits after the decimal point |
for v in [42, -7, 100]:
print(nfs(v, 4))
radians(degrees)
Converts an angle from degrees to radians.
| Parameter | Type | Description |
|---|---|---|
| degrees | float | Angle measured in degrees |
print(round(radians(180), 3)) print(round(radians(45), 3))
sin(angle)
Returns the sine of an angle. The input angle uses the current angleMode().
| Parameter | Type | Description |
|---|---|---|
| angle | float | The angle to evaluate |
createCanvas(400, 200)
while True:
background(30)
y = 100 + sin(frameCount * 0.05) * 60
fill(255)
circle(200, y, 30)
animate()
sq(x)
Squares a number.
| Parameter | Type | Description |
|---|---|---|
| x | float | The value to square |
print(sq(5)) print(sq(-3))
pow(n, e)
Raises a base to an exponent. Equivalent to n ** e in Python.
| Parameter | Type | Description |
|---|---|---|
| n | float | Base value |
| e | float | Exponent |
print(pow(2, 10)) print(pow(4, 0.5))
fract(n)
Returns the fractional part of a number (the part after the decimal point).
| Parameter | Type | Description |
|---|---|---|
| n | float | The value to extract the fraction from |
print(fract(3.75)) print(fract(-1.25))
tan(angle)
Returns the tangent of an angle. The input angle uses the current angleMode().
| Parameter | Type | Description |
|---|---|---|
| angle | float | The angle to evaluate |
print(round(tan(QUARTER_PI), 3)) angleMode(DEGREES) print(round(tan(45), 3))
Constants
Math
PI
HALF_PI
QUARTER_PI
TWO_PI
TAU
Angles
RADIANS
DEGREES
Shape & Image Modes
CORNER
CORNERS
CENTER
RADIUS
OPEN
CLOSE
CHORD
PIE
Stroke
ROUND
SQUARE
PROJECT
MITER
BEVEL
Text Alignment
LEFT
RIGHT
CENTER
TOP
BOTTOM
BASELINE
Text Style
BOLD
ITALIC
NORMAL
BOLDITALIC
Color Mode
RGB
HSB
HSL
Coordinate System
CARTESIAN
JAVASCRIPT
Shape Modes
POINTS
LINES
TRIANGLES
TRIANGLE_STRIP
TRIANGLE_FAN
QUADS
QUAD_STRIP
Key Codes
KEY_SPACE
KEY_ENTER
KEY_ESC
KEY_BACKSPACE
KEY_LEFT
KEY_RIGHT
KEY_UP
KEY_DOWN
KEY_SHIFT
KEY_CTRL
KEY_ALT
KEY_A … KEY_Z
KEY_0 … KEY_9