Drawing with Canvas: Paths, Styles, Text, Images, Transforms, Clipping and Pixels
Paint pixels with the canvas 2D API: getContext, paths, fill and stroke, sizing for devicePixelRatio, colors, gradients, line and text styles, shadows, compositing, save and restore, drawImage, transforms, clipping, ImageData pixel filters, animation loops and OffscreenCanvas.
kvi5hnuCode Sprout team member9 min readOn this page
A <canvas> element is a blank bitmap that JavaScript paints on with method calls. Unlike SVG (article 114), the canvas doesn't remember what you drew: once a shape is painted, it's just pixels. That makes canvas fast for games, charts with many thousands of points, image editing and visual effects, and it means you must redraw a scene to change it.
Getting a drawing context
Drawing methods live on a context object, not on the canvas element:
<canvas id="scene" width="400" height="240">A drawing of three shapes.</canvas>
const canvas = document.querySelector("#scene");
const ctx = canvas.getContext("2d"); // a CanvasRenderingContext2D
ctx.fillStyle = "#2563eb";
ctx.fillRect(20, 20, 120, 80); // x, y, width, height
ctx.beginPath();
ctx.arc(240, 60, 40, 0, Math.PI * 2); // a full circle
ctx.fillStyle = "#16a34a";
ctx.fill();
The text inside <canvas> is fallback content for browsers and assistive technology that can't show the drawing. Each canvas has exactly one 2D context: calling getContext("2d") again returns the same object. (getContext("webgl2") and "webgpu" return 3D APIs instead, usually used through libraries such as three.js.)
Size, coordinates and sharp drawings
The origin (0, 0) is the top-left corner, x grows to the right and y grows down. Coordinates can be fractional.
A canvas has two sizes:
- The bitmap size, set with the
widthandheightattributes or properties. This is how many pixels it stores; each pixel takes 4 bytes (RGBA). - The display size, set with CSS. The bitmap is stretched to fit it.
If they differ, the drawing is scaled and looks blurry. On high-density screens (devicePixelRatio of 2 or 3), make the bitmap larger than the CSS size, then scale the context so you can keep drawing in CSS pixels:
function setupCanvas(canvas, cssWidth, cssHeight) {
const ratio = window.devicePixelRatio || 1;
canvas.style.width = `${cssWidth}px`;
canvas.style.height = `${cssHeight}px`;
canvas.width = Math.round(cssWidth * ratio); // bitmap pixels
canvas.height = Math.round(cssHeight * ratio);
const ctx = canvas.getContext("2d");
ctx.scale(ratio, ratio); // draw in CSS pixels
return ctx;
}
Setting width or height, even to the current value, clears the canvas and resets all context state, including transforms and styles. That's why the scale is applied after resizing.
Paths
Anything beyond rectangles is drawn as a path: a sequence of subpaths built with "pen" commands, then filled or stroked:
function polygon(ctx, sides, cx, cy, radius, rotation = 0) {
ctx.moveTo(cx + radius * Math.sin(rotation), cy - radius * Math.cos(rotation));
for (let i = 1; i < sides; i++) {
const angle = rotation + (i * 2 * Math.PI) / sides;
ctx.lineTo(cx + radius * Math.sin(angle), cy - radius * Math.cos(angle));
}
ctx.closePath(); // line back to the first point
}
ctx.beginPath(); // start a new path, discarding the old one
polygon(ctx, 3, 60, 70, 45); // triangle
polygon(ctx, 6, 170, 70, 45); // hexagon (a second subpath)
ctx.fillStyle = "#e2e8f0";
ctx.strokeStyle = "#1e3a8a";
ctx.lineWidth = 4;
ctx.fill();
ctx.stroke();
Key path methods:
| Method | Adds |
|---|---|
beginPath() | nothing: discards the current path. Forgetting it is the most common canvas bug, because old shapes get redrawn |
moveTo(x, y) | starts a new subpath at a point |
lineTo(x, y) | a straight line from the current point |
arc(x, y, r, start, end, counterclockwise?) | a circular arc; angles in radians, measured clockwise from the positive x axis |
arcTo(x1, y1, x2, y2, r) | a rounded corner between two lines |
quadraticCurveTo, bezierCurveTo | Bézier curves, as in SVG's Q and C |
rect(x, y, w, h), roundRect(x, y, w, h, radii), ellipse(...) | complete shapes as subpaths |
closePath() | a line back to the start of the subpath |
fill() paints the inside of every subpath. When subpaths overlap or a path crosses itself, the nonzero winding rule decides what's "inside": a hole appears where an inner shape is drawn in the opposite direction from the outer one. Pass "evenodd" to fill() for the simpler rule that alternates inside and outside at each edge.
fillRect, strokeRect and clearRect draw rectangles directly without touching the current path. clearRect(0, 0, canvas.width, canvas.height) erases the canvas to transparent.
A Path2D object stores a path for reuse, and it even accepts SVG path syntax: new Path2D("M 10 10 L 90 10 L 50 80 Z"). ctx.isPointInPath(path, x, y) tests whether a point (for example, a click) falls inside a shape. That's how you do hit-testing on a canvas.
Graphics attributes
Styles are properties of the context, and they apply to everything drawn afterwards:
- Colors:
fillStyleandstrokeStyleaccept any CSS color ("#f00","rgb(0 0 0 / 50%)","oklch(70% 0.15 250)"), a gradient or a pattern. - Gradients:
createLinearGradient(x0, y0, x1, y1),createRadialGradient(...)andcreateConicGradient(angle, x, y), with color stops added bygradient.addColorStop(offset, color).createPattern(image, "repeat")tiles an image. - Lines:
lineWidth,lineCap("butt","round","square"),lineJoin("miter","round","bevel"),miterLimit, and dashes withsetLineDash([6, 4])andlineDashOffset(animate the offset for "marching ants"). - Text:
font(CSS shorthand, like"bold 16px system-ui"),textAlign,textBaseline,direction,letterSpacing. - Shadows:
shadowColor,shadowBlur,shadowOffsetX,shadowOffsetY. - Transparency and compositing:
globalAlphamultiplies all drawing by an opacity.globalCompositeOperationcontrols how new pixels combine with existing ones:"source-over"(the default),"destination-out"(erase),"multiply","lighter"and others. - Filters:
ctx.filter = "blur(4px) saturate(1.5)"uses CSS filter syntax.
const gradient = ctx.createLinearGradient(0, 0, 0, 200);
gradient.addColorStop(0, "#38bdf8");
gradient.addColorStop(1, "#1e3a8a");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 400, 200);
ctx.font = "600 28px system-ui";
ctx.textAlign = "center";
ctx.fillStyle = "white";
ctx.shadowColor = "rgb(0 0 0 / 40%)";
ctx.shadowBlur = 6;
ctx.fillText("Sky", 200, 110);
const width = ctx.measureText("Sky").width; // for layout: wrapping, centering, backgrounds
save() and restore()
Because all those settings are global to the context, a helper that changes them would affect later drawing code. ctx.save() pushes the entire graphics state (styles, transform, clipping region) onto a stack, and ctx.restore() pops it:
function drawBadge(ctx, x, y, label) {
ctx.save();
ctx.fillStyle = "crimson";
ctx.font = "bold 12px system-ui";
ctx.beginPath();
ctx.roundRect(x, y, ctx.measureText(label).width + 16, 22, 11);
ctx.fill();
ctx.fillStyle = "white";
ctx.fillText(label, x + 8, y + 15);
ctx.restore(); // the caller's styles are back
}
The current path is not part of the saved state. ctx.reset() returns everything to the defaults and clears the canvas.
Images
drawImage copies an image onto the canvas. The source can be an <img> (once it has loaded), another canvas, a <video> frame, or an ImageBitmap:
const photo = new Image();
photo.src = "/img/tea.jpg";
await photo.decode(); // wait until it can be drawn
ctx.drawImage(photo, 10, 10); // natural size
ctx.drawImage(photo, 10, 10, 160, 120); // scaled into a 160×120 box
ctx.drawImage(photo, 0, 0, 300, 300, 200, 10, 100, 100); // crop a 300×300 source area into 100×100
To export the result, canvas.toDataURL("image/png") returns a data: URL, and canvas.toBlob(callback, "image/webp", 0.9) produces a Blob you can upload with fetch (article 117) or offer as a download.
Drawing an image from another origin without CORS permission taints the canvas. After that, toDataURL, toBlob and getImageData throw a SecurityError, so pages can't read pixels of images they weren't allowed to see.
Transforms
Every context has a current transformation matrix that maps the coordinates you pass to actual canvas pixels. Instead of computing rotated positions yourself, you transform the coordinate system and draw in simple local coordinates:

translate(x, y)moves the origin.rotate(angle)turns the axes clockwise by an angle in radians.scale(sx, sy)stretches them. A negative value mirrors.transform(a, b, c, d, e, f)multiplies by an arbitrary matrix;setTransform(...)replaces it;resetTransform()restores the identity;getTransform()returns aDOMMatrix.
Each call is applied on top of the existing transform, so the order matters. The math behind it, in plain JavaScript:
// A 2D affine transform as [a, b, c, d, e, f], the same layout canvas uses:
// x' = a*x + c*y + e, y' = b*x + d*y + f
const identity = [1, 0, 0, 1, 0, 0];
function multiply([a1, b1, c1, d1, e1, f1], [a2, b2, c2, d2, e2, f2]) {
return [
a1 * a2 + c1 * b2, b1 * a2 + d1 * b2,
a1 * c2 + c1 * d2, b1 * c2 + d1 * d2,
a1 * e2 + c1 * f2 + e1, b1 * e2 + d1 * f2 + f1,
];
}
const translate = (m, x, y) => multiply(m, [1, 0, 0, 1, x, y]);
const rotate = (m, angle) => multiply(m, [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0]);
const scale = (m, sx, sy) => multiply(m, [sx, 0, 0, sy, 0, 0]);
function apply([a, b, c, d, e, f], x, y) {
const round = (n) => Math.round(n * 100) / 100 + 0;
return [round(a * x + c * y + e), round(b * x + d * y + f)];
}
// like ctx.translate(100, 50); ctx.rotate(Math.PI / 2); ctx.scale(2, 2)
let m = translate(identity, 100, 50);
console.log("after translate:", apply(m, 10, 0));
m = rotate(m, Math.PI / 2);
console.log("after rotate: ", apply(m, 10, 0));
m = scale(m, 2, 2);
console.log("after scale: ", apply(m, 10, 0));
// order matters: rotate first, then translate
let n = rotate(identity, Math.PI / 2);
n = translate(n, 100, 50);
console.log("rotate, then translate:", apply(n, 10, 0));
after translate: [ 110, 50 ]
after rotate: [ 100, 60 ]
after scale: [ 100, 70 ]
rotate, then translate: [ -50, 110 ]
The last line shows the effect of order: after rotating first, translate(100, 50) moves along the rotated axes, sending the point off the left edge of the canvas. (The + 0 in round turns -0 into 0.)
The usual pattern is save, transform to the object's position and rotation, draw it around (0, 0), then restore. Combined with recursion, transforms make fractals simple. Each branch of this tree is drawn in its own rotated and shrunk coordinate system:
function branch(ctx, length, depth) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -length);
ctx.stroke();
if (depth === 0) return;
ctx.translate(0, -length); // move to the tip of this branch
for (const angle of [-0.45, 0.35]) {
ctx.save();
ctx.rotate(angle);
ctx.scale(0.7, 0.7);
branch(ctx, length, depth - 1); // same code, smaller rotated coordinate system
ctx.restore();
}
}
ctx.save();
ctx.translate(200, 230); // the trunk starts at the bottom center
ctx.lineWidth = 6;
branch(ctx, 70, 8);
ctx.restore();
Line widths scale along with the coordinate system, so the branches get thinner automatically.
Clipping
ctx.clip() turns the current path into a mask. Later drawing only appears inside it, until a restore() removes it:
ctx.save();
ctx.beginPath();
ctx.arc(80, 80, 60, 0, Math.PI * 2);
ctx.clip(); // only the circle is paintable now
ctx.drawImage(photo, 20, 20, 120, 120); // a round avatar
ctx.restore();
Pixel manipulation
getImageData(x, y, w, h) returns an ImageData whose data is a Uint8ClampedArray with four bytes (red, green, blue, alpha, each 0 to 255) per pixel, row by row. You can change the bytes and write them back with putImageData(imageData, x, y). The byte loop itself is plain JavaScript:
// A 3 × 1 "image": red, green, blue pixels, fully opaque (RGBA bytes)
const pixels = new Uint8ClampedArray([
255, 0, 0, 255,
0, 255, 0, 255,
0, 0, 255, 255,
]);
function grayscale(data) {
for (let i = 0; i < data.length; i += 4) {
const luminance = 0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2];
data[i] = data[i + 1] = data[i + 2] = luminance; // alpha (i + 3) is unchanged
}
return data;
}
console.log([...grayscale(pixels)].join(" "));
const clamped = new Uint8ClampedArray(2);
clamped[0] = 300; // stored as 255
clamped[1] = -20.6; // stored as 0
console.log(clamped);
54 54 54 255 182 182 182 255 18 18 18 255
Uint8ClampedArray(2) [ 255, 0 ]
Green looks much brighter than blue to the human eye, which the luminance weights reflect. The clamped array type rounds and clamps values to 0–255 automatically, so filters don't need bounds checks. In the browser, the filter is applied like this:
const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
grayscale(image.data);
ctx.putImageData(image, 0, 0);
getImageData and putImageData work in bitmap pixels and ignore the transform. Note that ctx.filter = "grayscale(1)" does this particular effect faster. Pixel loops are for effects that filters can't do, such as color analysis, edge detection or blending successive frames.
Animation
Canvas animation means clearing and redrawing every frame. requestAnimationFrame schedules a callback just before the browser's next repaint. It runs at the display's refresh rate, pauses in background tabs, and receives a high-resolution timestamp:
let x = 0;
let last = performance.now();
function frame(now) {
const seconds = (now - last) / 1000; // time-based, so speed doesn't depend on frame rate
last = now;
x = (x + 120 * seconds) % canvas.width; // 120 pixels per second
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, 100, 20, 0, Math.PI * 2);
ctx.fill();
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
For heavy rendering, canvas.transferControlToOffscreen() hands the canvas to a Web Worker (article 120) as an OffscreenCanvas, so drawing doesn't block the main thread. createImageBitmap() decodes images off the main thread.
Common questions
Why is my canvas drawing blurry?
The bitmap size (width/height) doesn't match the display size times devicePixelRatio. Size the bitmap in device pixels and scale() the context, as in setupCanvas above.
Why do previous shapes get drawn again when I call fill()?
You didn't call beginPath(), so the new shape was added to the old path, and fill() paints the whole path. Call beginPath() before each new shape.
How do I detect clicks on shapes?
Canvas has no per-shape events. Keep your own list of shapes and test the pointer position with math or with ctx.isPointInPath(path2d, x, y), converting event.offsetX/offsetY to canvas coordinates first.
Why does getImageData throw a SecurityError?
The canvas is tainted by an image loaded from another origin without CORS permission. Serve the image with CORS headers and set img.crossOrigin = "anonymous" before setting src.
Summary
- Get a context with
canvas.getContext("2d"); the origin is top-left with y pointing down; size the bitmap bydevicePixelRatiofor sharpness (resizing resets everything). - Build paths with
beginPath,moveTo,lineTo,arc, curves andclosePath, thenfill()and/orstroke();Path2Dstores reusable shapes. - Styles (
fillStyle, gradients, line, text, shadow,globalAlpha,globalCompositeOperation,filter) are context state;save()/restore()scope them. drawImagedraws, scales and crops images;toBlob/toDataURLexport the canvas; cross-origin images taint it.translate,rotateandscalecompose in order and let you draw in local coordinates;clip()masks drawing.getImageData/putImageDataexpose RGBA bytes in aUint8ClampedArray; animate withrequestAnimationFrameand time-based movement.
Practice Questions
A canvas has width="300" and CSS width: 600px. What happens to a 1-pixel line?
Answer
The 300-pixel bitmap is stretched to 600 CSS pixels, so the line becomes 2 CSS pixels wide and blurry. Match the bitmap size to the CSS size (times devicePixelRatio).
How many bytes does getImageData(0, 0, 100, 50).data contain, and where is the alpha of the pixel at (x = 3, y = 2)?
Answer
100 × 50 × 4 = 20,000 bytes. The pixel's red byte is at (2 * 100 + 3) * 4 = 812, so its alpha is at index 815.
Why does this rotate the square around the top-left corner of the canvas instead of around its own center, and how do you fix it?
ctx.rotate(Math.PI / 4);
ctx.fillRect(200, 200, 50, 50);
Answer
rotate turns the axes around the current origin, which is (0, 0). Translate to the square's center first, rotate, and draw centered on the new origin:
ctx.save();
ctx.translate(225, 225);
ctx.rotate(Math.PI / 4);
ctx.fillRect(-25, -25, 50, 50);
ctx.restore();
Why is requestAnimationFrame better than setInterval(draw, 16) for animation?
Answer
It's synchronized with the display's refresh, so frames aren't skipped or doubled. It adapts to 120 Hz and other refresh rates, pauses in background tabs to save power, and passes a precise timestamp for time-based movement.
Previous: Scripting SVG: Inline Vector Graphics, createElementNS, Paths and a Data-Driven Pie Chart
Next: Audio, Location and History: Web Audio, URLs, the History API and the Navigation API

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.