Skip to content

Canvas: draw images, charts and text

shotcup:canvas draws images, charts and text with a Canvas 2D context and writes PNG, JPEG, GIF and APNG files, with no browser. Turn it on with engine: { canvas: true } in the run request, then import { createCanvas, Path2D, decodeImage, loadImage, imageInfo, fonts, saveAnimation } from "shotcup:canvas";. Files the code writes under /out come back with the run (see Artifacts).

Shapes and images are methods on the canvas (each returns the canvas); text and paths go through canvas.getContext("2d"), a Canvas 2D context with real fonts, colour emoji and anti-aliased fill and stroke, rounded rectangles, Path2D objects and hit testing, clipping, dashed lines, gradients, patterns, shadows, compositing, filters, drawImage, ImageData and transforms. The context follows the HTML Standard; each section below links the part it follows and states where it differs. The methods on the canvas itself are Shotcup's own.

Colours

Colours follow CSS Color Level 4, with the limits and the stricter argument rules stated here. A colour is exactly one argument: a CSS colour string ("#rgb", "#rgba", "#rrggbb", "#rrggbbaa", "rgb(15 23 42)", "rgba(15, 23, 42, 0.5)", "rgb(15 23 42 / 50%)", "hsl(222, 47%, 11%)", "hsl(222 47 11)", "hsla(...)", a named colour such as "steelblue" or "transparent"), a CSS Color 4 colour ("oklch(0.62 0.21 260)", Tailwind's palette, "oklab(...)", "lab(...)", "lch(...)", "hwb(194 30% 20%)", "color(display-p3 0.3 0.6 0.2)" and the other color() spaces: srgb, srgb-linear, display-p3, a98-rgb, prophoto-rgb, rec2020, xyz, xyz-d50, xyz-d65; "none" components and "/ alpha" work as in CSS) or an array [r, g, b] / [r, g, b, a] with channels 0-255 (a = 255 is opaque). The canvas is sRGB: other spaces are converted and clipped to it, and ctx.fillStyle reads back as "#rrggbb" or "rgba(...)". Anything else (objects, unknown names, separate numbers) throws a TypeError naming the argument position. Every method checks its argument count and types (numbers must be finite: NaN or Infinity throws), so a mistake fails loudly instead of shifting later arguments. The exceptions are canvas.toDataURL, toBlob and convertToBlob, which take their arguments as a browser does.

Canvas

The methods below are Shotcup's own: the HTML Standard's canvas element has none of them, apart from width, height, getContext("2d"), toDataURL and toBlob, and convertToBlob from OffscreenCanvas, which keep their meaning. The shape methods on the canvas (fillRect, strokeRect, strokeLine, fillCircle) take their colour as an argument and use none of the context's state.

  • createCanvas(width, height, background?) -> canvas (transparent when no background; at most 16384 px per side and 64 Mpx; pixels count against the run's JS heap)
  • createCanvas(width, height, { pixels, background }) starts from RGBA bytes (a Uint8Array or Uint8ClampedArray of width * height * 4, row by row; a wrong length throws a TypeError)
  • canvas.width, canvas.height
  • clear(color?) (transparent when omitted)
  • fillRect(x, y, w, h, color)
  • strokeRect(x, y, w, h, color, lineWidth = 1) (border inside the rectangle)
  • strokeLine(x1, y1, x2, y2, color, width = 1) or (..., color, { width, antialias = true })
  • fillCircle(cx, cy, r, color)
  • getContext("2d") -> the 2d context for text and paths (below; the same object every time)
  • getPixel(x, y) -> [r, g, b, a]; setPixel(x, y, color); pixels() -> Uint8Array (an RGBA copy)
  • putPixels(x, y, width, height, rgba) writes a rectangle of RGBA bytes (Uint8Array or Uint8ClampedArray, width * height * 4) as given, without blending, clipped to the canvas; putPixels(rgba) writes the whole canvas. One call replaces a loop of setPixel calls.
  • canvas.data -> the canvas's own RGBA bytes as a Uint8Array, without a copy: writes change the canvas and later drawing shows in it (the same array every time)
  • drawImage(image, x, y, width?, height?, { alpha, filter }?) or drawImage(image, x, y, { width, height, alpha, filter }) (source-over; image is any canvas, including a decoded image; resamples with filter (default "bilinear"; "nearest" keeps pixel art crisp) when the size differs; returns the canvas it drew on)
  • resize(width, height, filter = "bilinear") (filter: nearest, bilinear, bicubic, lanczos; 0 for one side keeps the aspect ratio), crop(x, y, w?, h?), rotate(90 | 180 | 270), flip("horizontal" | "vertical"), grayscale() and clone() each return a new canvas
  • toPNG(level = 6 | { level, filter: "auto" | "none" | "adaptive", palette, dither }) -> Uint8Array (level 0-9; "auto", the default, leaves flat graphics unfiltered and filters photo-like images). A canvas of at most 256 colours (alpha included) is written as an indexed PNG with the same pixels, 21 to 66 % smaller in our test scenes; otherwise RGB or RGBA. palette makes it smaller at the cost of exact colours, with encodeGIF's names: a number from 2 to 256 (at most that many colours, a median cut over the pixels, alpha included; exact when the canvas has no more), "exact" (a RangeError past 256 colours) or an array of colours used as given, in that order (each pixel takes the nearest; include a transparent colour to keep transparency). dither: "floyd-steinberg" (or true) smooths gradients with a palette. An 800x450 dial of 931 colours: 15.4 KB by default, 8.0 KB at palette: 256, 6.3 KB at 64
  • toJPEG(quality = 90 | { quality, background, progressive }) -> Uint8Array (photos: a JPEG is a fraction of the PNG's size and encodes faster)
  • toDataURL(type = "image/png", quality?) -> "data:image/png;base64,..." ("image/jpeg" with quality 0-1, default 0.92, over black as in a browser; any other type is a PNG, indexed when the colours fit, as toPNG()). It takes its arguments exactly as a browser's canvas does: type is converted to a string, quality counts only for JPEG and only as a number from 0 to 1, and anything else, extra arguments and options objects included, is ignored. So there is no palette option: toDataURL("image/png", { palette: 64 }) is the default PNG. For a palette, encode with toPNG and wrap the bytes: "data:image/png;base64," + canvas.toPNG({ palette: 64 }).toBase64(). At most 16,777,216 characters (a RangeError beyond), and the string counts against the run's memory: write files with save() instead
  • toBlob(callback, type = "image/png", quality?) encodes the canvas now, as toDataURL does for the same type and quality, and calls your function after your script's current code with a Blob of the image (blob.type is "image/png" or "image/jpeg"). It runs as a promise job queued when toBlob returns, so before a promise callback your code queues after the call (a browser runs it after them); to wait for it, wrap it in a promise or use convertToBlob. A callback that is not a function is a TypeError; an error the callback throws fails the run like any uncaught error
  • convertToBlob({ type = "image/png", quality }?) -> Promise<Blob>, the same image as a promise: options is undefined, null or an object, and any error (a wrong receiver or options, a type whose toString throws) rejects the promise instead of throwing. Read the bytes with await blob.bytes() or await blob.arrayBuffer(). Blob is a global: new Blob(parts, { type }), size, type, slice, text(), arrayBuffer(), bytes() (no stream method)
  • save(path, options?) encodes by extension (.png with toPNG's options, .jpg and .jpeg with toJPEG's), writes into the sandbox filesystem (creating directories) and returns the bytes written
  • getInfo() -> { width, height, format }

Text

Text follows the HTML Standard's drawing text and text styles. Where this differs, the text below says so: there is no shaping and no wrapping, and a mistake in an argument throws where a browser ignores the call.

JavaScript
const ctx = canvas.getContext("2d");
ctx.font = "600 24px Inter, sans-serif"; // [style] [weight] size[/line-height] family[, family]
ctx.fillStyle = "#f8fafc";               // any colour form above
ctx.textAlign = "center";                // start | end | left | right | center
ctx.textBaseline = "middle";             // alphabetic | top | hanging | middle | ideographic | bottom
ctx.fillText("Revenue Q3", 400, 30);     // fillText(text, x, y, maxWidth?): x, y is the anchor point
ctx.strokeStyle = "#0f172a"; ctx.lineWidth = 2;
ctx.strokeText("Revenue Q3", 400, 30);   // the same text's outline, in strokeStyle and the line style
const m = ctx.measureText("Revenue Q3"); // m.width, m.actualBoundingBoxAscent, ..., m.missingGlyphs

The context's state: font (default "10px sans-serif"), fillStyle (default "#000000"), globalAlpha (0-1), textAlign, textBaseline, direction ("ltr" | "rtl": rtl only swaps start and end), fontKerning ("auto" | "normal" | "none"), letterSpacing ("2px", "0.05em"); save() and restore() keep and bring back that state. fillRect(x, y, w, h) on the context uses fillStyle and globalAlpha; clearRect(x, y, w, h) makes the rectangle transparent (both as in the standard's rectangles). An invalid assignment (ctx.font = "big", ctx.fillStyle = "reddish") is ignored and the previous value kept, as in a browser, and the run result lists it under warnings (code "invalid-style-value").

  • fillText(text, x, y, maxWidth?) draws one line (newlines become spaces; there is no wrapping); with maxWidth the text is condensed horizontally to fit.
  • strokeText(text, x, y, maxWidth?) strokes the outline of the same text: the same layout, then the outline stroked as one path in strokeStyle (a colour, gradient or pattern) with lineWidth, lineJoin, miterLimit, lineCap, setLineDash and lineDashOffset, under the transform, globalAlpha, the clip and the shadow; it does not touch the current path. Fill and stroke the same text at the same place for outlined letters (fillText first, so the stroke's inner half shows). The built-in fonts and nearly all of the font catalogue are drawn from one outline per letter (their overlapping contours are merged), so a stroke shows no seams inside a letter; a face loaded with fonts.load keeps what its file holds, and a letter made of overlapping contours shows their inner edges, as in a browser. With maxWidth the stroke is condensed with the text. A missing glyph is stroked as its box and a colour emoji, which has no outline, draws nothing; its shadow follows the exact shadowOffset (no snapping to whole pixels). The outlines of one call take at most 1,000,000 points (a RangeError: draw the text in parts), and the stroke is bounded as any stroke is.
  • measureText(text) returns the TextMetrics of the current font: width, actualBoundingBoxLeft, actualBoundingBoxRight, actualBoundingBoxAscent, actualBoundingBoxDescent, fontBoundingBoxAscent, fontBoundingBoxDescent, emHeightAscent, emHeightDescent, alphabeticBaseline, hangingBaseline, ideographicBaseline, and missingGlyphs: the characters no font covers (drawn as boxes).
  • Sizes in px, pt, em and rem (1em = 16px); at most 1024px.
  • One fillText, strokeText or measureText call takes at most 100,000 characters (a longer text throws a RangeError); the layout counts against the run's JS heap.
  • A glyph with more than 12,000 outline points or 2,000 contours is skipped and listed in the run's warnings (code "glyph-budget").

Fonts on every runtime:

familyweightsfor
Inter (also sans-serif, system-ui)400, 700interface text
Inter Tabular400numbers in columns: every digit has the same width
JetBrains Mono (monospace)400, 700code
Noto Serif (serif)400serif text
Noto Sans400, 700the fallback for Latin, Greek and Cyrillic characters Inter lacks

They cover Latin (with Vietnamese), Greek and Cyrillic, punctuation, currency, arrows, maths and box drawing. Weights match the CSS way (500 draws with 400; 600, 800 and 900 with 700; 100-300 with 400); an italic without an italic face is slanted. Each character falls back along the font list of ctx.font, then Inter, Noto Sans, the colour emoji, and finally a box; the run's warnings lists the boxed code points (code "missing-glyphs"). Arabic, Hebrew, Indic scripts, Thai and CJK are not supported (no shaping): they draw as boxes or unjoined letters.

Colour emoji (Noto Color Emoji, Unicode 18.0) work in any font: ZWJ sequences (๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ), skin tones (๐Ÿ‘๐Ÿฝ), flags (๐Ÿ‡ฉ๐Ÿ‡ช, ๐Ÿด๓ ง๓ ข๓ ณ๓ ฃ๓ ด๓ ฟ) and keycaps (1๏ธโƒฃ). Characters with a text default (ยฉ โ„ข โ†”) draw as text unless followed by U+FE0F (ยฉ๏ธ). Emoji ignore fillStyle; globalAlpha applies.

Google Fonts: the 47 most popular families (Roboto, Open Sans, Lato, Montserrat, Poppins, Playfair Display, ...) are on every runtime at 400 and 700, so ctx.font can name them directly; fonts.load fetches another weight of them ("300 32px Roboto"). Any other Latin/Greek/Cyrillic family of the Google Fonts catalogue loads by name: declare it in the run's fonts (["Playfair Display:400,700", "Lora:400italic"]) so it is ready before the script starts, or await fonts.load("700 32px 'Playfair Display'") inside the script (the wait counts against the run's timeout). A run uses at most 2 such faces on Free, 12 on Pro and 32 on Scale, declared and loaded together (1 MiB, 32 MiB and 64 MiB of font files); a load past that is a RangeError. ctx.font never waits: a family that is not loaded falls back and the run's warnings say so (code "font-fallback"). A saved sandbox keeps the font catalogue version it was created with: declare the fonts it uses when its text must render the same after a catalogue update. fonts.check(font) tells whether every family of a font string is usable now; fonts.families() lists them.

There is no wrapping or ellipsis: fit text with measureText, for example

JavaScript
// words into lines no wider than maxWidth in the current font
const wrap = (ctx, text, maxWidth) => {
  const lines = [];
  let line = "";
  for (const word of text.split(" ")) {
    const next = line === "" ? word : `${line} ${word}`;
    if (line !== "" && ctx.measureText(next).width > maxWidth) {
      lines.push(line);
      line = word;
    } else line = next;
  }
  return line === "" ? lines : [...lines, line];
};

Paths

Paths follow the HTML Standard's building paths, drawing paths to the canvas and line styles. The last two points of the list give the limits and say where the arguments are stricter than the standard.

JavaScript
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(40, 200);
ctx.lineTo(120, 60);
ctx.quadraticCurveTo(200, 20, 260, 120);
ctx.bezierCurveTo(300, 190, 200, 240, 40, 200);
ctx.closePath();
ctx.fillStyle = "rgba(37, 99, 235, 0.8)";
ctx.fill(); // fill(fillRule?): "nonzero" (the default) or "evenodd"
ctx.strokeStyle = "#0f172a";
ctx.lineWidth = 4;
ctx.lineJoin = "round";
ctx.stroke();
ctx.beginPath(); // a new path; the old one stays drawn
ctx.arc(320, 80, 30, 0, 2 * Math.PI); // angles in radians, clockwise from the x axis
ctx.fill();
  • beginPath() starts an empty path; moveTo(x, y), lineTo(x, y), quadraticCurveTo(cpx, cpy, x, y), bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y), arc(x, y, radius, startAngle, endAngle, counterclockwise?), arcTo(x1, y1, x2, y2, radius) (a rounded corner), ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise?), rect(x, y, w, h), roundRect(x, y, w, h, radii?) and closePath() add to it, as in a browser.
  • roundRect's radii: a number, { x, y } (an elliptical corner) or a list of 1 to 4 of them, in CSS border-radius order (4: upper left, upper right, lower right, lower left; 3: upper left, upper right and lower left, lower right; 2: upper left and lower right, upper right and lower left); radii too large for the rectangle shrink together, a negative w or h mirrors it, and afterwards the current point is (x, y). A negative radius or another list length is a RangeError.
  • fill(fillRule?) fills the path in fillStyle; stroke() outlines it in strokeStyle with lineWidth (default 1), lineJoin ("miter" | "round" | "bevel", default "miter"), miterLimit (default 10) and lineCap ("butt" | "round" | "square", default "butt"); strokeRect(x, y, w, h) outlines a rectangle without touching the path. Everything is anti-aliased and drawn source-over with globalAlpha.
  • Coordinates are canvas pixels until a transform changes them (below); pixel centres sit at .5, so a 1 px line at y = 10.5 is crisp. The path stays after fill and stroke until beginPath(), and holds at most 1,000,000 points once curves are flattened (more is a RangeError); its memory counts against the run's limit. One fill or stroke makes at most 4,000,000 edges (a fill one a point, a stroke about 4 to 10), fewer when the run's memory holds less: a path past that is a RangeError, so draw very large strokes in parts. Filling and stroking count against the run's time and instruction limits.
  • Arguments must be finite numbers (a browser ignores the call; here it is a TypeError), a negative radius is a RangeError, and counterclockwise must be true or false (a browser converts any value). Assignments to strokeStyle, lineWidth, lineJoin, lineCap and miterLimit follow the text properties: an invalid value is ignored and listed (code "invalid-style-value"), and save() and restore() keep them.

Path2D

A Path2D is a path you keep. Build it once, then fill, stroke or clip it as often as you like, at any size or place, without touching the context's current path. It follows the HTML Standard's Path2D objects; the differences are listed below. Path2D is exported by shotcup:canvas, and import "shotcup:canvas/global" makes it a global, with DOMMatrix and DOMPoint.

JavaScript
import { createCanvas, Path2D } from "shotcup:canvas";

// a heart from SVG path data, drawn eight times larger than its 24 x 24 box
const heart = new Path2D(
  "M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",
);
const canvas = createCanvas(256, 256, "#f8fafc");
const ctx = canvas.getContext("2d");
ctx.save();
ctx.translate(32, 32);
ctx.scale(8, 8);
ctx.fillStyle = "#fecdd3";
ctx.fill(heart);
ctx.strokeStyle = "#e11d48";
ctx.lineWidth = 0.5;
ctx.stroke(heart);
// true: the point is in canvas pixels, and the path is tested under this call's transform
const inside = ctx.isPointInPath(heart, 128, 128);
ctx.restore();
canvas.save("/out/heart.png");
  • new Path2D() is empty. new Path2D(path) copies another Path2D; the copy and its source are independent afterwards, in both directions. new Path2D(d) reads SVG path data, the d of an SVG <path>, with SVG 2's grammar: every command, relative and absolute, elliptical arcs, numbers written together such as 1-2 and .5.5, and arc flags without separators. As in SVG, the segments before the first error are kept. Any other value is converted to a string first, as in a browser, so new Path2D(5) is an empty path.
  • The path methods are moveTo, lineTo, quadraticCurveTo, bezierCurveTo, arc, arcTo, ellipse, rect, roundRect and closePath. They take the same arguments as the context's and check them in the same way: a non-finite number is a TypeError and a negative radius a RangeError, where a browser ignores such calls.
  • addPath(path, transform?) adds a copy of another path, mapped by transform: a DOMMatrix2DInit, that is { a, b, c, d, e, f }, { m11, m12, m21, m22, m41, m42 } or what ctx.getTransform() returns. Without one the path is added as it is. A matrix with a NaN or infinite value adds nothing and is listed as "invalid-style-value" (a browser ignores it silently). Anything else is a TypeError.
  • After addPath, and after reading path data, the next call starts a new subpath at the last point, as the HTML Standard says. Chrome continues the last contour instead, so a lineTo straight after new Path2D(d) or addPath can fill differently there than in Chrome. Start with moveTo to draw the same everywhere.
  • ctx.fill(path, fillRule?), ctx.stroke(path) and ctx.clip(path, fillRule?) fill, stroke or clip the path under the transform current at that call, so scale(8) draws it eight times larger, with curves smooth at that size. They leave the context's current path as it is. The clip, patterns, gradients, shadows, compositing, filter and dashes apply as they do to the current path.
  • A Path2D holds at most 1,000,000 entries: each call counts as one, and so does each segment of path data (an elliptical arc as one to four, a quarter turn each), plus one for the data as a whole; each addPath adds the other path's entries plus three. A call or an addPath that would go past it is a RangeError and adds nothing. Its memory counts against the run's memory while it lives. Each use is bounded like the current path: at most 1,000,000 points once curves are flattened, and at most 4,000,000 edges for one fill or stroke.
  • A path keeps its flattened points for the transform of its last use, so drawing the same path many times under one transform flattens it once. Any change to the path drops them.

Hit testing

ctx.isPointInPath(x, y, fillRule?), ctx.isPointInPath(path, x, y, fillRule?), ctx.isPointInStroke(x, y) and ctx.isPointInStroke(path, x, y) answer whether a point is inside the current path or a Path2D. They follow the HTML Standard's isPointInPath and isPointInStroke.

  • The point is in canvas pixels, and the transform does not move it; the path is tested under the transform current at the call.
  • isPointInPath uses the fill rule ("nonzero" by default, or "evenodd") with open subpaths closed. isPointInStroke uses lineWidth, lineJoin, lineCap, miterLimit and the dashes, under the transform, as stroke() would draw them.
  • A point on the outline is inside. The clip does not count.
  • As in a browser, x and y are converted to numbers, and NaN or an infinity answers false.
  • Curves are tested as drawn: flattened to within 0.1 px.

Clipping, dashes and patterns

Clipping, dashes and patterns follow the HTML Standard's drawing paths to the canvas, line styles and fill and stroke styles; the list below says where they are stricter.

JavaScript
// a striped drop-off segment: a hatch tile as a pattern, cut to a rounded bar with clip()
const tile = createCanvas(12, 12, "#fee2e2");
const t = tile.getContext("2d");
t.strokeStyle = "#f87171";
t.lineWidth = 3;
t.beginPath();
t.moveTo(-12, 12); t.lineTo(0, 0);
t.moveTo(0, 12); t.lineTo(12, 0);
t.moveTo(12, 12); t.lineTo(24, 0);
t.stroke();
const hatch = ctx.createPattern(tile, "repeat");
ctx.save();
ctx.beginPath(); // the bar's outline, its top corners rounded with arcTo
ctx.moveTo(100, 300); ctx.lineTo(100, 126); ctx.arcTo(100, 120, 106, 120, 6);
ctx.lineTo(154, 120); ctx.arcTo(160, 120, 160, 126, 6); ctx.lineTo(160, 300); ctx.closePath();
ctx.clip(); // clip(fillRule?): "nonzero" or "evenodd"; the path stays
ctx.fillStyle = hatch;
ctx.fillRect(100, 120, 60, 80);
ctx.restore(); // the clip ends with the save() it was made under
ctx.setLineDash([4, 4]); // dash and gap lengths in pixels
ctx.lineDashOffset = 0;
ctx.beginPath();
ctx.moveTo(40, 120.5);
ctx.lineTo(560, 120.5);
ctx.stroke();
ctx.setLineDash([]); // solid again
  • clip(fillRule?) intersects the clipping region with the current path's fill (open subpaths closed); every fill, stroke, fillRect, strokeRect, fillText, strokeText and clearRect of the context stays inside it, anti-aliased at its edges. Only restore() widens it again, so clip between save() and restore(). The canvas's own methods (canvas.fillRect, drawImage, putPixels, ...) are not the context's drawing and are never clipped.
  • setLineDash(segments) takes an array of lengths: an odd list is used twice over, a list with a negative, NaN or infinite length is ignored and listed as "invalid-style-value", more than 1,024 lengths is a RangeError; getLineDash() returns the list; lineDashOffset shifts where it starts. Each subpath starts the pattern again, every dash gets lineCap, a 0-length dash with round caps is a dot, and a list of zeros strokes solid. A dash list too fine for a long path is a RangeError: use longer dashes or stroke in parts.
  • createPattern(image, repetition) takes a canvas (or a loaded image, which is one) and "repeat" (also "" or null), "repeat-x", "repeat-y" or "no-repeat", and copies the image as it is now. Assign it to fillStyle or strokeStyle; it paints fills, strokes and text (fillText and strokeText) in its own colours (globalAlpha still applies; colour emoji keep theirs); setTransform(matrix?) on it moves, scales or turns its tiles (below).
  • Stricter than a browser: setLineDash takes only an array of numbers and createPattern only a canvas and a string or null (anything else is a TypeError, an unknown repetition a SyntaxError), and lineDashOffset takes only a finite number (a string such as "3" is ignored and listed).
  • A pattern's tiles start at the origin of the user space (the canvas's top-left corner without a transform) and turn and scale with the transform when you fill; a clip stays where it was drawn. A clip's coverage mask (a byte per pixel of its box; none when the region is a rectangle on whole pixels or fills its box) and a pattern's copy count against the run's memory limit while they are held; past it the run ends as "resource-limit".

Gradients, pattern transforms and shadows

Gradients and pattern transforms follow the HTML Standard's fill and stroke styles, and shadows its shadows. The list below states the differences: how colours are interpolated and where a call is stricter.

JavaScript
// a card on a gradient, its shadow, a ring in a conic gradient and a title filled with a gradient
const bg = ctx.createLinearGradient(0, 0, 640, 360);
bg.addColorStop(0, "#0f172a");
bg.addColorStop(1, "#4338ca");
ctx.fillStyle = bg;
ctx.fillRect(0, 0, 640, 360);
ctx.save();
ctx.shadowColor = "rgba(15, 23, 42, 0.5)";
ctx.shadowBlur = 32; // the blur's standard deviation is half of it, in canvas pixels
ctx.shadowOffsetY = 16;
ctx.fillStyle = "#f8fafc";
ctx.beginPath();
ctx.roundRect(60, 60, 520, 240, 24);
ctx.fill();
ctx.restore(); // the shadow is part of the saved state
const ring = ctx.createConicGradient(-Math.PI / 2, 180, 180); // angle in radians, clockwise
ring.addColorStop(0, "#22d3ee");
ring.addColorStop(1, "#a78bfa");
ctx.strokeStyle = ring;
ctx.lineWidth = 16;
ctx.beginPath();
ctx.arc(180, 180, 70, 0, 2 * Math.PI);
ctx.stroke();
const title = ctx.createLinearGradient(280, 0, 560, 0);
title.addColorStop(0, "#f59e0b");
title.addColorStop(1, "#ec4899");
ctx.fillStyle = title;
ctx.font = "700 44px Inter";
ctx.fillText("Gradients", 280, 190);
  • createLinearGradient(x0, y0, x1, y1), createRadialGradient(x0, y0, r0, x1, y1, r1) and createConicGradient(startAngle, x, y) return a CanvasGradient; its addColorStop(offset, color) places a stop at an offset from 0 to 1 (a RangeError outside it, an IndexSizeError in a browser) in any colour the context takes (a SyntaxError for anything else, as in a browser). The coordinates are in the user space of the transform when you fill or stroke. Before the first stop the colour is the first stop's, after the last the last's, stops at one offset make a hard edge (the first added is nearer the start), and a gradient without stops paints nothing. Colours are interpolated linearly in sRGB without premultiplying alpha, as the standard says: red at alpha 0 to blue is purple at half alpha, not blue. Stops are clipped to sRGB as fillStyle colours are (Chrome interpolates in another colour space when a stop is written in lab(), oklab(), lch(), oklch() or color(); this follows the standard, so write such a gradient with several stops where it matters). A gradient holds at most 65,536 colour stops (a RangeError), and they count against the run's memory.
  • The radial gradient is the cone between its two circles: the part before the start circle is the first colour, the part beyond the end circle the last, nothing outside the cone is painted, a negative radius is a RangeError and the same circle twice paints nothing. The conic gradient starts at startAngle (0 points along the x axis) and turns clockwise, as CSS conic-gradient does. A linear gradient whose two points are one point paints nothing.
  • Assign a gradient to fillStyle or strokeStyle, as a pattern: it paints fill(), stroke(), fillRect, strokeRect, fillText and strokeText (colour emoji keep their own colours), under globalAlpha, the clip and the transform you fill with; reading fillStyle back returns the gradient, and save() and restore() keep it. One gradient serves any canvas.
  • pattern.setTransform(matrix?) sets the pattern's own matrix, a DOMMatrix or { a, b, c, d, e, f } (no argument is the identity), applied before the context's transform when you fill: the tiles scale, turn and shift with it. A matrix with a NaN or infinite value is ignored and listed as "invalid-style-value"; a matrix that cannot be inverted paints nothing.
  • shadowColor (a colour, transparent black by default), shadowBlur (0 or more, 0 by default), shadowOffsetX and shadowOffsetY (finite, 0 by default) draw a shadow under fill(), stroke(), fillRect, strokeRect, fillText, strokeText and drawImage when the colour's alpha is not 0 and the blur or an offset is not 0 (clearRect and putImageData make none, and the canvas's own methods never do). The shadow is the shape's alpha, moved by the offset, blurred with a Gaussian of standard deviation shadowBlur / 2 and drawn in shadowColor, with globalAlpha and the clip, under the shape: a translucent shape, a gradient, a pattern or an image makes the shadow its own alpha makes. The offset and the blur are in canvas pixels and not affected by the transform. A fillRect under a translation sits on whole pixels, and so does its shadow's source; text under a translation draws on a rounded baseline, so a fractional vertical offset moves its shadow by whole pixels. A shadowBlur above 512 blurs as that one does, and a shadow too faint to show costs nothing. shadowBlur and the offsets convert a number as a browser does (a boolean, a numeric string and null count; gradient and transform arguments stay strict numbers, as everywhere in the canvas). Invalid values (a negative or non-finite blur, a non-finite offset, a colour that does not parse) are ignored and listed ("invalid-style-value"), and save() and restore() keep the four.
  • A shadow's plane (a byte a pixel, twice with a blur) is the moved shape's box and the canvas, each widened by three standard deviations, where they meet, so a large shadowBlur costs memory and time even for a small shape (blur 512 on a tiny shape: about 150 ms and 440,000 instructions); it is reserved from the run's memory while it is made, and its blur counts against the run's time and instruction limits like any fill: a shadow that does not fit is a RangeError (draw the shape in parts or lower the blur), and blurring a canvas-sized shape with a large shadowBlur costs about as many instructions as filling it ten times.

Compositing and blend modes

Compositing follows the HTML Standard's compositing and the blend modes Compositing and Blending Level 1. The differences, where there are any, are stated in the list below.

JavaScript
// a photo-like backdrop, a multiplied shade, a screened glow, a text knocked out of a panel, a page drawn behind it all
ctx.fillStyle = "#38bdf8";
ctx.fillRect(0, 0, 640, 360);
ctx.globalCompositeOperation = "multiply"; // anything drawn from here on multiplies what is there
ctx.fillStyle = "#9ca3af";
ctx.fillRect(0, 0, 640, 360);
ctx.globalCompositeOperation = "screen";
const glow = ctx.createRadialGradient(480, 60, 4, 480, 60, 220);
glow.addColorStop(0, "rgba(253, 224, 71, 0.9)");
glow.addColorStop(1, "rgba(253, 224, 71, 0)");
ctx.fillStyle = glow;
ctx.fillRect(0, 0, 640, 360);
ctx.globalCompositeOperation = "destination-out"; // erases: the text becomes a hole
ctx.font = "700 72px Inter";
ctx.fillText("Hole", 60, 200);
ctx.globalCompositeOperation = "destination-over"; // draws behind what is there
ctx.fillStyle = "#f8fafc";
ctx.fillRect(0, 0, 640, 360);
ctx.globalCompositeOperation = "source-over"; // the default again
  • globalCompositeOperation (default "source-over", kept by save() and restore()) takes the operators of the Canvas 2D standard, in lower case: the Porter-Duff operators source-over, source-in, source-out, source-atop, destination-over, destination-in, destination-out, destination-atop, lighter (adds the colours), copy, xor and clear (which the web-platform-tests list too), and the blend modes multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity (Compositing and Blending Level 1). Any other value, another case ("Multiply"), "plus-lighter" included, and any other type is ignored and listed ("invalid-style-value"), as in a browser.
  • Every fill(), stroke(), fillRect, strokeRect, fillText, strokeText and drawImage uses it, and so does a shadow (the shadow is composited first, then the shape, both with the operator). A call that draws nothing (an empty rectangle, a path with no point, a maxWidth of 0, a transform that cannot be inverted, a drawImage of an empty rectangle) changes nothing, whatever the operator. A path of points but no area (a lone moveTo, a zero-length line) is composited as an empty shape, so the operators that clear past the shape clear the clip's box; Chrome keeps the canvas for some of these paths. clearRect and putImageData ignore it, and the canvas's own methods (canvas.fillRect, drawImage, putPixels, ...) are not the context's drawing and never use it.
  • The standard's drawing model: the shape is drawn into a transparent layer, then composited onto the canvas inside the clip, with globalAlpha. So source-in, source-out, destination-in, destination-atop and copy change the whole clip box, not only the shape: fillRect(10, 10, 5, 5) under "copy" leaves nothing but that square (inside the clip), and under "destination-in" keeps only what is under the square. The other operators and the blend modes change nothing where the shape is transparent ("clear", which is not in the standard's list, is bounded as in Chrome: it clears the shape and nothing else, but with a shadow Chrome clears the clip's whole box, and so does this). A blend mode mixes the colour of the shape with what is under it where that is opaque, and is plain source-over where it is not.
  • The layer is the shape's box less what the canvas and the clip cannot show (and, with a shadow, where the shadow reads it); its pixels are reserved from the run's memory while the call lasts, and a layer that does not fit, or is wider than 65,536 pixels (a shape far larger than the canvas under a shadow offset that reaches far from it), is a RangeError (draw the shape in parts, or use a clip). Its work is charged per pixel (a few dozen native instructions) with the deadline, the instruction limit and a cancel checked every row: a full-canvas fill under a blend mode costs about as much as filling it a dozen times, and the non-separable modes (hue, saturation, color, luminosity) about twice that.
  • The result is within a level or two of a browser's (the arithmetic is the standard's, in doubles, rounded once; a browser keeps premultiplied bytes).

Filters

Filters follow the HTML Standard's filters and the functions of Filter Effects Module Level 1. The list below states what is not supported and where this differs from a browser.

JavaScript
// a photo with a softened, desaturated, brightened look, and a card with a hard drop shadow
ctx.filter = "grayscale(60%) contrast(1.1) brightness(1.15)";
ctx.drawImage(photo, 0, 0, 640, 360);
ctx.filter = "blur(3px)"; // every draw after this is blurred by 3px (the standard deviation)
ctx.fillStyle = "rgba(15, 23, 42, 0.5)";
ctx.fillRect(40, 40, 200, 120);
ctx.filter = "drop-shadow(0 6px 12px rgba(0, 0, 0, 0.4)) saturate(120%)";
ctx.fillStyle = "#f8fafc";
ctx.fillRect(300, 80, 240, 140);
ctx.filter = "none";
  • filter (default "none", kept by save() and restore()) takes what the CSS filter property takes, as text: "none" or a list of filter functions applied in the order written: blur(<length>) (a Gaussian whose standard deviation is the length), brightness(), contrast(), grayscale(), invert(), opacity(), saturate() and sepia() (a number or a percentage; brightness, contrast and saturate may go above 1, the others stop at 1; none may be negative), hue-rotate(<angle>) and drop-shadow(<offset-x> <offset-y> <blur>? <color>?) (the shape over a copy of its alpha moved by the offset, blurred by the deviation and coloured; black without a colour). Every spelling CSS accepts is accepted (case, units such as em, rem, turn and rad, calc(), any colour the context takes), and the text reads back as you wrote it. The functions work on straight sRGB colour with the alpha untouched, except opacity() and blur() and drop-shadow(), which change it.
  • Not supported: url() references to SVG filters. A list with one, a text CSS refuses (blur(5), blur(-1px), a missing argument, an unknown function, inherit, an empty string), one of more than the limit (at most 32 functions and 8,192 bytes of text), and a value that is not a string is ignored and listed ("invalid-style-value"), the previous filter kept. A blur beyond 256px blurs as 256px does. Lengths in em and the like are relative to ctx.font's size; currentcolor is black.
  • It applies to every fill(), stroke(), fillRect, strokeRect, fillText, strokeText and drawImage (clearRect and putImageData ignore it, the canvas's own methods never use it), in the order of the standard's drawing model: the shape is drawn into a layer, the filter works on it, then the shadow (shadowColor and the rest) of the filtered shape is made, and both are composited with globalCompositeOperation inside the clip. globalAlpha scales the shape before the filter (so a drop-shadow's copy and the shape add up as two translucent shapes do, as in a browser). Lengths are in canvas pixels: the transform does not scale them, as a browser's. Font-relative lengths (em, ex) follow ctx.font as it is when the shape is drawn, and viewport units (vw, vh) are zero, because a canvas here has no page around it.
  • The layer is widened by the chain's reach (a blur of s pixels reaches three standard deviations, a drop-shadow its offset and its blur) and is reserved from the run's memory like any layer; a blur also takes two more bytes a pixel while it runs. What does not fit the run's memory (a chain of thirty-two 256px blurs on a large canvas), or reaches past 65,536 pixels on a side (a drop-shadow offset of tens of thousands of pixels), is a RangeError; the work is charged (a blur about as much as a shadow's per channel) with the deadline, the instruction limit and a cancel checked, so a full-canvas blur costs about as much as filling the canvas a few dozen times.
  • The result is within a level of a browser's for the colour functions and within a few levels where a blur fades (the Gaussian here, Skia's boxes there).

Transforms

Transforms follow the HTML Standard's transformations. The list below states the differences.

JavaScript
// a label turned to read upwards beside an axis, then a dial's ticks
ctx.save();
ctx.translate(40, 300);   // the origin moves to (40, 300)
ctx.rotate(-Math.PI / 2); // radians, clockwise on the canvas
ctx.fillText("Revenue", 0, 0);
ctx.restore();            // the transform is part of the saved state
for (const i of Array(12).keys()) {
  ctx.save();
  ctx.translate(200, 200);
  ctx.rotate((i * Math.PI) / 6);
  ctx.fillRect(80, -1, 12, 2);
  ctx.restore();
}
  • translate(x, y), rotate(angle), scale(x, y) and transform(a, b, c, d, e, f) multiply the current transformation matrix; setTransform(a, b, c, d, e, f) or setTransform(matrix) replaces it, where matrix is a DOMMatrix or a plain { a, b, c, d, e, f } (setTransform() is the identity; a 3D matrix gives its 2D part), resetTransform() resets it, and getTransform() returns a new DOMMatrix holding it. save() and restore() keep it.
  • Everything the context draws goes through it: paths (each point when it is added, as in a browser, so moving the transform between lineTo calls bends the path), fillRect, strokeRect, clearRect, fillText, strokeText (glyph outlines, colour emoji and boxes; a pure translation draws exactly as at the moved point), drawImage, patterns (as the transform is when you fill) and clip(). Line widths, dashes and caps are in the user space of the transform when you stroke: scale(4, 1) makes vertical lines four times as wide as horizontal ones. getImageData and putImageData ignore it, as in a browser.
  • A call with a NaN or infinite argument is ignored and listed as "invalid-style-value" (a browser ignores it silently); anything but numbers is a TypeError. Under a transform that cannot be inverted (a scale of 0) nothing is drawn and clip() changes nothing.

Write modern TypeScript first: arrow functions, const/let and for (const x of ...) (Array(n).keys() for counted loops), ===. The default engine.compat: "strict" profile also parses function, var, while, classic for and line breaks without ;, but not == or arguments. A run that fails on a construct its profile leaves out carries a hint saying what to write instead.

DOMMatrix and DOMPoint

import { DOMMatrix, DOMMatrixReadOnly, DOMPoint, DOMPointReadOnly } from "shotcup:canvas", or import "shotcup:canvas/global" once to make them (and Path2D) globals for code written for a browser. They are the Geometry Interfaces a browser has: a 4x4 matrix whose fields a to f and m11 to m44 you read (and set, on a DOMMatrix), with is2D and isIdentity, and a point with x, y, z and w.

JavaScript
import { createCanvas, DOMMatrix, DOMPoint } from "shotcup:canvas";

const ctx = createCanvas(400, 400).getContext("2d");
ctx.translate(200, 200);
ctx.rotate(Math.PI / 6);
const m = ctx.getTransform(); // a DOMMatrix
const corner = m.transformPoint(new DOMPoint(50, 0)); // where (50, 0) lands on the canvas
const back = m.inverse().transformPoint(corner); // and back: x 50, y 0 (to rounding)
ctx.setTransform(new DOMMatrix().translate(10, 10).scale(2)); // a matrix built up front
  • new DOMMatrix() and new DOMMatrixReadOnly() are the identity, DOMMatrix([a, b, c, d, e, f]) a 2D matrix, sixteen numbers (column by column) a 3D one; DOMMatrix.fromMatrix({ ... }), fromFloat32Array(array) and fromFloat64Array(array) make one from a dictionary or a typed array. A DOMMatrixReadOnly cannot be changed.
  • These return a new DOMMatrix: translate(tx, ty, tz), scale(sx, sy, sz, ox, oy, oz), scaleNonUniform(sx, sy), scale3d(s, ox, oy, oz), rotate(degrees) or rotate(x, y, z), rotateFromVector(x, y), rotateAxisAngle(x, y, z, degrees), skewX(degrees), skewY(degrees), multiply(other), flipX(), flipY() and inverse() (every field NaN when the matrix cannot be inverted).
  • On a DOMMatrix these change it in place and return it: translateSelf(), scaleSelf(), scale3dSelf(), rotateSelf(), rotateFromVectorSelf(), rotateAxisAngleSelf(), skewXSelf(), skewYSelf(), multiplySelf(other), preMultiplySelf(other) and invertSelf().
  • transformPoint(point) and point.matrixTransform(matrix) return a new DOMPoint; DOMPoint(x, y, z, w), DOMPointReadOnly(x, y, z, w) and DOMPoint.fromPoint({ x, y }) make one. toFloat32Array() and toFloat64Array() give the sixteen fields column by column; toJSON() gives a plain object.
  • toString() writes matrix(a, b, c, d, e, f), or matrix3d(...) for a 3D matrix (a field that is not finite is an InvalidStateError). The constructor and setMatrixValue(string) read that form back (a list of matrix() and matrix3d(), "none" or ""); other CSS transforms such as "rotate(45deg)" are a SyntaxError: build them with the methods. Arguments are converted to numbers as in a browser. Logging a matrix with console.log prints {} (the fields are on the prototype): print m.toString() or m.toJSON() instead.
  • Not provided: DOMRect, DOMQuad, and the SVGMatrix, SVGPoint and WebKitCSSMatrix names.

drawImage and ImageData on the context

Drawing images follows the HTML Standard's drawing images and image smoothing, and ImageData its pixel manipulation. The differences from the standard are in the list below.

JavaScript
const photo = loadImage("/in/photo.jpg");
ctx.drawImage(photo, 20, 20);                     // at its size
ctx.drawImage(photo, 20, 20, 320, 180);           // scaled into a rectangle
ctx.drawImage(photo, 100, 50, 200, 200, 360, 20, 120, 120); // a source rectangle into a destination one
ctx.imageSmoothingEnabled = false;                // pixel art: nearest neighbour
const data = ctx.getImageData(0, 0, 100, 100);    // { width, height, data: Uint8ClampedArray (RGBA), colorSpace }
for (const i of Array(data.data.length / 4).keys()) data.data[i * 4 + 3] = 128;
ctx.putImageData(data, 200, 200);                 // written as is
  • ctx.drawImage(image, dx, dy), (image, dx, dy, dw, dh) or (image, sx, sy, sw, sh, dx, dy, dw, dh) draws a canvas (createCanvas, loadImage, decodeImage, or the context's own canvas) source-over in globalAlpha, inside the clip, with anti-aliased edges at fractional positions. A source rectangle past the image is cut to it (the destination shrinks in proportion); negative sizes extend left or up (they do not mirror). imageSmoothingEnabled (default true) and imageSmoothingQuality ("low" and "medium": bilinear, "high": bicubic) choose the sampling; shrinking an image more than 2:1 is filtered first, so a thumbnail does not alias. It takes 3, 5 or 9 arguments (others are a TypeError). canvas.drawImage (above) is the canvas's own method with explicit options and no context state.
  • ctx.getImageData(sx, sy, sw, sh) copies the pixels (outside the canvas: transparent black), straight alpha; ctx.putImageData(imagedata, dx, dy, dirtyX?, dirtyY?, dirtyWidth?, dirtyHeight?) writes them without blending, globalAlpha or the clip, as in a browser; ctx.createImageData(sw, sh) or (imagedata) makes transparent image data. A size of 0 is a RangeError, as is one past the canvas bounds; the data counts against the run's memory. For whole canvases, canvas.data and putPixels (above) avoid the copy.

Images in

Give the run its input images as files, never as text you transcribe (the request's files):

  • { path: "/in/photo.jpg", url: "https://example.com/photo.jpg" } imports a file the service downloads before the run (https on port 443 only, capped per file by the plan);
  • { path: "/in/logo.png", content: "<base64>", encoding: "base64" } sends the bytes inline (at most 1 MiB decoded per file);
  • POST /api/v1/sandboxes and PUT /api/v1/sandboxes/:id/files take the same forms, so a saved sandbox can keep the image for later runs.
JavaScript
// a run request with engine: { canvas: true } and
// files: [{ path: "/main.js", content: <this> }, { path: "/in/photo.jpg", url: "https://..." }]
import { loadImage } from "shotcup:canvas";
const photo = loadImage("/in/photo.jpg");
const thumb = photo.resize(640, 0, "lanczos"); // 0 keeps the aspect ratio
const ctx = thumb.getContext("2d");
ctx.font = "700 40px Inter";
ctx.fillStyle = "#ffffff";
ctx.fillText("Hello ๐Ÿ‘‹", 24, 64);
thumb.save("/out/thumb.jpg", { quality: 85 }); // JPEG for photos: far smaller than PNG
  • decodeImage(bytes | path) -> canvas (PNG, JPEG, GIF, BMP; bytes is a Uint8Array or ArrayBuffer), or an SvgImage for SVG
  • loadImage(path) -> canvas (the same, from the sandbox filesystem)
  • imageInfo(bytes | path) -> { width, height, format } (header only, nothing decoded)
  • A damaged image is a TypeError that says what is wrong; a JPEG's also names its class in brackets (structure, marker, frame, scan, table, unsupported or bound): "decodeImage: jpeg image could not be decoded (marker): it has a second SOI marker".
  • A decoded image is a canvas: draw on it, resize() it, or drawImage() it onto another canvas.
  • An SVG is not a bitmap: decodeImage and loadImage of SVG bytes or a file return an SvgImage with width, height (the document's own size), format "svg" and render({ width, height, scale, background }) -> canvas. drawImage(svg, x, y, w, h) draws it at the destination size and transform, sharp at any size; createPattern tiles it at its own size (render({ scale }) for a larger tile). Shapes, paths, gradients, patterns, clip paths, masks, markers, embedded images and text (text, tspan and textPath, in the 2d context's fonts, left to right), filters, <style> sheets and CSS shapes in clip-path are drawn. href reads run files and data: URLs only, never the network. What it leaves out (an unknown element, a foreignObject, vertical text, an image it cannot read) is listed in the run's warnings (code "svg-unsupported"). See /docs/svg.

fs.readFileSync(path) without an encoding returns a Uint8Array, so any binary input file decodes with decodeImage(fs.readFileSync(path)) or loadImage(path). Base64 text the script itself builds decodes with Uint8Array.fromBase64 (prefer it to atob, which builds a string first). Resize a large photo before drawing it many times, and save photos as JPEG.

Bytes

  • crc32(bytes) and adler32(bytes) -> number, to check that data arrived intact
  • deflate(bytes, level = 6) -> Uint8Array (zlib stream)
  • Uint8Array.fromBase64(text) and bytes.toBase64(); btoa(binaryString) and atob(base64) also exist

Animation

Frames are canvases of one size; the encoders write them natively (no JS GIF or PNG code needed):

JavaScript
import { createCanvas, saveAnimation, encodeGIF } from "shotcup:canvas";
const frames = [];
for (const i of Array(16).keys()) {
  const c = createCanvas(128, 128);           // transparent background
  c.fillCircle(16 + i * 6, 64, 12, "#f97316");
  frames.push(c);
}
saveAnimation("/out/ball.gif", frames, { delay: 80 });             // .gif, or .apng / .png for APNG
saveAnimation("/out/ball_4x.png", frames, { delay: 80, scale: 4 }); // pixel art: upscaled while encoding
const bytes = encodeGIF(frames, { delay: [500, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 500] });
  • encodeGIF(frames, { delay, loop, scale, palette, dither, alphaThreshold }?) -> Uint8Array
  • encodeAPNG(frames, { delay, loop, scale, crop, level }?) -> Uint8Array
  • saveAnimation(path, frames, options?) encodes by extension (.gif, .apng, .png), writes the file and returns the bytes written
  • frames: an array of canvases, or { canvas, delay } items; every frame has the first one's size
  • delay: milliseconds per frame (default 100), one number or an array with one per frame; GIF keeps hundredths of a second, and browsers show delays under 20 ms slower
  • loop: how many times it plays, 0 (default) forever
  • scale: an integer nearest-neighbour upscale done while encoding (no big canvases needed)
  • GIF: one palette for all frames, exact when the frames together use at most 256 colours, otherwise a median cut (palette "exact" refuses instead; an array of colours is also accepted); pixels with alpha below alphaThreshold (128) are transparent; dither: "floyd-steinberg" (or true) smooths gradients after a median cut
  • APNG is lossless: full alpha, an indexed palette when the colours fit; crop: true stores only the rectangle that changed since the previous frame; level is the deflate level (6)
  • Limits per call: frames Free 100, Pro 1,000, Scale 5,000; pixels after scale, all frames together, Free 8 Mpx, Pro 128 Mpx, Scale 512 Mpx; output Free 4 MiB, Pro 16 MiB, Scale 64 MiB. Past one it is a RangeError.

Memory

Two limits apply to a run. The JS heap (Free 32 MiB, Pro 256 MiB, Scale 256 MiB) is the engine's budget of charged bytes: strings, array buffers, typed arrays, canvases and codec buffers; an allocation past it fails. The resident cap (Free 104 MiB, Pro 384 MiB, Scale 384 MiB, the heap x 1.25 + 64 MiB) bounds the run's actual memory above what the sandbox held when it started, because the engine does not charge everything (array elements, object properties, garbage not yet collected). A run past it ends as a resource limit with "resident memory limit exceeded". The run's metrics report peakRssKb (its resident peak, the sandbox's memory at the start included) next to residentLimitKb (the cap in the same terms): compare those two, not peakRssKb with the JS heap. Short-lived arrays and objects in tight loops are what push resident memory up; draw with canvas methods and bulk putPixels rather than per-pixel arrays.

Artifacts

Files written under /out come back with the run: canvas.save("/out/chart.png") or fs.writeFileSync("/out/chart.png", canvas.toPNG()) (import fs from "fs"; readFileSync, writeFileSync and mkdirSync work on the sandbox filesystem). Each artifact gets a URL (a capability link that works without the API key and expires with the plan's retention: Free 1 day, Pro 7 days, Scale 30 days, Platform 90 days). Pass artifacts: "private" when the output is personal: the URLs then answer only with the API key (Authorization: Bearer).

Time

Runs are deterministic by default: Date.now() and performance.now() return 0, and new Date() and Temporal.Now.instant() are 1970-01-01. Pass deterministic: false for the real clock (Temporal is much faster than the legacy Date).

Example: the canvas-image template

The template reads /data/metrics.json ({ title, subtitle, status, series: [{ label, value }] }) and /assets/logo.png.b64; replace those reads with literals to run it as one file.

JavaScript
// A status card from /data/metrics.json with shotcup:canvas (engine.canvas):
// a bar chart with an anti-aliased trend line, text through the Canvas 2D
// context (real fonts: Inter, and Inter Tabular for aligned digits), a
// status badge, and the bundled logo (a PNG stored as base64 text) decoded,
// resized and composited with alpha. Writes /out/card.png and /out/card.jpg.
import fs from "fs";
import { createCanvas, decodeImage } from "shotcup:canvas";

const data = JSON.parse(fs.readFileSync("/data/metrics.json", "utf8"));
const W = 800;
const H = 420;
const card = createCanvas(W, H, "#0f172a");
const ctx = card.getContext("2d");

// background bands and frame
for (const i of Array(14).keys()) card.fillRect(0, i * 30, W, 15, "rgba(255, 255, 255, 0.025)");
card.strokeRect(0, 0, W, H, "#1e293b", 4);

// title and subtitle
ctx.fillStyle = "#f8fafc";
ctx.font = "700 30px Inter, sans-serif";
ctx.fillText(data.title, 32, 56);
ctx.fillStyle = "#94a3b8";
ctx.font = "16px Inter, sans-serif";
ctx.fillText(data.subtitle, 34, 84);

// chart area: gridlines with right-aligned tabular labels
const chart = { x: 64, y: 110, w: 504, h: 260 };
const max = Math.max(...data.series.map((p) => p.value));
const step = chart.w / data.series.length;
ctx.font = "13px 'Inter Tabular'";
ctx.textAlign = "right";
ctx.textBaseline = "middle";
for (const g of Array(5).keys()) {
  const y = chart.y + chart.h - (g * chart.h) / 4;
  card.strokeLine(chart.x, y, chart.x + chart.w, y, "#1e293b");
  ctx.fillStyle = "#64748b";
  ctx.fillText(String(Math.round((g * max) / 4)), chart.x - 10, y);
}
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.font = "600 13px Inter";
const points = data.series.map((p, i) => {
  const h = Math.round((p.value / max) * (chart.h - 20));
  const x = chart.x + i * step + step * 0.2;
  card.fillRect(x, chart.y + chart.h - h, step * 0.6, h, "#38bdf8");
  ctx.fillStyle = "#94a3b8";
  ctx.fillText(p.label, x + step * 0.3, chart.y + chart.h + 10);
  return [x + step * 0.3, chart.y + chart.h - h - 14];
});
for (const i of Array(points.length - 1).keys()) {
  const [a, b] = [points[i], points[i + 1]];
  card.strokeLine(a[0], a[1], b[0], b[1], "#f472b6", 3);
}
for (const [x, y] of points) {
  card.fillCircle(x, y, 6, "#f472b6");
  card.fillCircle(x, y, 2.5, "#0f172a");
}
card.strokeLine(chart.x, chart.y + chart.h, chart.x + chart.w, chart.y + chart.h, "#cbd5e1", 2);

// status badge: a pill sized to its measured label
ctx.font = "700 16px Inter";
const label = `Status ${data.status}`;
const text = ctx.measureText(label);
const badge = { w: Math.ceil(text.width) + 48, h: 40, y: 300 };
badge.x = W - badge.w - 36;
const tone = data.status === "passing" ? "#16a34a" : "#dc2626";
card.fillRect(badge.x + 20, badge.y, badge.w - 40, badge.h, tone);
card.fillCircle(badge.x + 20, badge.y + 20, 20, tone);
card.fillCircle(badge.x + badge.w - 20, badge.y + 20, 20, tone);
ctx.fillStyle = "#f8fafc";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(label, badge.x + badge.w / 2, badge.y + badge.h / 2);

// the bundled logo: decode, resize, composite with alpha, plus a faint large copy behind the badge
const logo = decodeImage(Uint8Array.fromBase64(fs.readFileSync("/assets/logo.png.b64", "utf8").trim()));
const small = logo.resize(112, 112, "lanczos");
card.drawImage(small, W - 112 - 40, 36);
card.drawImage(logo.grayscale(), 600, 110, 160, 160, { alpha: 0.12 });

const png = card.toPNG();
fs.mkdirSync("/out", { recursive: true });
fs.writeFileSync("/out/card.png", png);
const jpgBytes = card.save("/out/card.jpg", { quality: 85 });
console.log(
  JSON.stringify({
    card: card.getInfo(),
    logo: logo.getInfo(),
    pngBytes: png.length,
    jpgBytes,
    bars: data.series.length,
    badgeWidth: badge.w,
  }),
);

This page as Markdown: /docs/canvas.md