Getting started with Canvas 2D
Getting Started with Canvas 2D
Section titled “Getting Started with Canvas 2D”The Canvas 2D backend lets you generate raster images using the browser’s
Canvas API. Your main() function creates an OffscreenCanvas, draws on it,
and returns it — the backend encodes the result as a PNG for preview and export.
Your first script
Section titled “Your first script”Open the Modelling tab and click New project, choosing Canvas 2D as the backend. Hit ▶ Run to render the starter design.
function main({ size }) { const canvas = new OffscreenCanvas(size, size) const ctx = canvas.getContext('2d')
ctx.fillStyle = '#0d0d1a' ctx.fillRect(0, 0, size, size)
ctx.fillStyle = '#e94560' ctx.beginPath() ctx.arc(size / 2, size / 2, size * 0.35, 0, Math.PI * 2) ctx.fill()
return canvas}
module.exports = { main }Three things every Canvas 2D script does:
- Create an
OffscreenCanvaswith the desired pixel dimensions. - Get a 2D rendering context with
canvas.getContext('2d'). - Return the canvas from
main().
OffscreenCanvas is available in Web Workers, which is why it works here —
unlike document.createElement('canvas'), which requires a DOM.
The coordinate system
Section titled “The coordinate system”Canvas uses the same convention as SVG: origin at the top-left, y-axis pointing downward.
(0,0) ──────────── (width, 0) │ │ │ │(0, height) ── (width, height)Drawing rectangles
Section titled “Drawing rectangles”The simplest drawing operations work directly on rectangles:
// Filled rectanglectx.fillStyle = '#e94560'ctx.fillRect(x, y, width, height)
// Outlined rectanglectx.strokeStyle = '#4fc3f7'ctx.lineWidth = 2ctx.strokeRect(x, y, width, height)
// Clear a region (makes it transparent)ctx.clearRect(x, y, width, height)Everything more complex uses the path API. Build a path with beginPath(),
then describe it with movement commands, then paint it with fill() or
stroke():
ctx.beginPath()ctx.moveTo(50, 200)ctx.lineTo(200, 50)ctx.lineTo(350, 200)ctx.closePath() // connects back to moveTo point
ctx.fillStyle = 'rgba(233, 69, 96, 0.6)'ctx.strokeStyle = '#ffffff'ctx.lineWidth = 2ctx.fill()ctx.stroke()Common path methods:
| Method | What it draws |
|---|---|
moveTo(x, y) |
Start a new sub-path at (x, y) |
lineTo(x, y) |
Straight line from current point |
arc(cx, cy, r, start, end) |
Circular arc |
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) |
Cubic Bézier |
quadraticCurveTo(cpx, cpy, x, y) |
Quadratic Bézier |
rect(x, y, w, h) |
Rectangle sub-path |
For a full circle: arc(cx, cy, r, 0, Math.PI * 2).
Styles
Section titled “Styles”Set styles before drawing. They persist until changed:
ctx.fillStyle = '#e94560' // CSS colour stringctx.strokeStyle = 'rgba(255,255,255,0.5)'ctx.lineWidth = 3ctx.lineCap = 'round' // 'butt' | 'round' | 'square'ctx.lineJoin = 'round' // 'miter' | 'round' | 'bevel'ctx.globalAlpha = 0.8 // applies to all subsequent drawingGradients
Section titled “Gradients”// Linear gradientconst grad = ctx.createLinearGradient(0, 0, size, size)grad.addColorStop(0, '#e94560')grad.addColorStop(1, '#0f3460')ctx.fillStyle = gradctx.fillRect(0, 0, size, size)
// Radial gradientconst radial = ctx.createRadialGradient(cx, cy, 0, cx, cy, r)radial.addColorStop(0, '#ffffff')radial.addColorStop(1, 'transparent')ctx.fillStyle = radialTransforms
Section titled “Transforms”Move the origin, rotate, or scale before drawing, then restore afterwards:
ctx.save() // push current state (transform, styles, etc.)
ctx.translate(cx, cy) // move origin to (cx, cy)ctx.rotate(angle) // rotate by angle radiansctx.scale(sx, sy) // scale axes
ctx.fillRect(-w/2, -h/2, w, h) // drawn relative to new origin
ctx.restore() // pop back to saved statesave() and restore() stack — every save() must be matched by a
restore(). This makes it easy to draw many repeated shapes with different
transforms without transforms accumulating:
for (let i = 0; i < 8; i++) { ctx.save() ctx.translate(cx, cy) ctx.rotate((i / 8) * Math.PI * 2) ctx.translate(radius, 0) ctx.fillRect(-10, -10, 20, 20) ctx.restore()}ctx.font = 'bold 24px sans-serif'ctx.textAlign = 'center' // 'left' | 'center' | 'right'ctx.textBaseline = 'middle' // 'top' | 'middle' | 'bottom' | 'alphabetic'ctx.fillStyle = '#ffffff'ctx.fillText('Hello', cx, cy)Parameters
Section titled “Parameters”Export a getParameterDefinitions() to add live controls:
const getParameterDefinitions = () => [ { name: 'size', type: 'number', widget: 'slider', caption: 'Canvas size', default: 800, min: 200, max: 2048 }, { name: 'rings', type: 'number', widget: 'slider', caption: 'Rings', default: 12, min: 1, max: 40 }, { name: 'color', type: 'color', caption: 'Ring colour', default: '#e94560' },]
function main({ size, rings, color }) { const canvas = new OffscreenCanvas(size, size) const ctx = canvas.getContext('2d') const cx = size / 2, cy = size / 2
ctx.fillStyle = '#0d0d1a' ctx.fillRect(0, 0, size, size)
for (let i = rings; i > 0; i--) { const r = (i / rings) * (size * 0.45) ctx.globalAlpha = i / rings ctx.strokeStyle = color ctx.lineWidth = 1.5 ctx.beginPath() ctx.arc(cx, cy, r, 0, Math.PI * 2) ctx.stroke() }
ctx.globalAlpha = 1 return canvas}Exporting
Section titled “Exporting”Click ↓ Export in the viewer toolbar to download the image as a .png
file. Use Share → Copy as PNG to copy it to the clipboard.
Next steps
Section titled “Next steps”- Try the Noise and colour tutorial for procedural pixel-level generation using simplex-noise and chroma-js.
- Use Edit imports… to see the available libraries:
simplex-noise,chroma-js, and@javasculpt/lib/font-loader.