Skip to content
Tutorials Center
My learning

Topics

HTML Reference ยท Scripting

Canvas 2D context reference

Every CanvasRenderingContext2D method and property in grouped tables: rectangles, paths, text, images, transforms, compositing, pixels, state and styles.

A <canvas> element is a blank bitmap until you draw on it. canvas.getContext("2d") returns a CanvasRenderingContext2D object, and everything on this page is a method or property of that object (usually stored in a variable named ctx). The context is a state machine: you set styles such as fillStyle and lineWidth, then call drawing methods that use the current state.

JavaScript
const ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "tomato";       // set state...
ctx.fillRect(10, 10, 100, 50);  // ...then draw with it

Coordinates are in canvas pixels, with (0, 0) at the top-left corner and y growing downward. Angles are in radians (Math.PI is half a turn).

Try it

Rectangles, a path and an arc

The rectangle methods draw immediately. Everything else is a path: beginPath() starts a new one, commands such as moveTo(), lineTo() and arc() add to it, and nothing appears until fill() or stroke(). The transparent window shows the page background through the canvas, because clearRect() erases pixels to transparent.

Rectangles

Member Description
fillRect(x, y, w, h) Fills a rectangle with fillStyle. Does not touch the current path.
strokeRect(x, y, w, h) Outlines a rectangle with strokeStyle and the line settings.
clearRect(x, y, w, h) Erases the area to transparent black.
rect(x, y, w, h) Adds a rectangle to the current path.
roundRect(x, y, w, h, radii) Adds a rounded rectangle to the path. radii is a number or a list of 1โ€“4 values (like CSS border-radius).

Paths

Member Description
beginPath() Empties the current path. Call it before each new shape, or old subpaths are filled and stroked again.
moveTo(x, y) Starts a new subpath at a point.
lineTo(x, y) Adds a straight line.
arc(x, y, r, start, end, ccw = false) Adds a circular arc around (x, y) from angle start to end (radians, 0 = pointing right, clockwise by default).
arcTo(x1, y1, x2, y2, r) Adds an arc of radius r that rounds the corner between the current point, (x1, y1) and (x2, y2).
ellipse(x, y, rx, ry, rotation, start, end, ccw) Adds an elliptical arc.
quadraticCurveTo(cpx, cpy, x, y) Adds a quadratic Bรฉzier curve with one control point.
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) Adds a cubic Bรฉzier curve with two control points.
closePath() Adds a line back to the start of the subpath. (It does not end the path; beginPath() does.)
fill(fillRule), fill(path, fillRule) Fills the current path or a Path2D. fillRule is "nonzero" (default) or "evenodd".
stroke(), stroke(path) Outlines the current path or a Path2D.
clip(fillRule), clip(path, fillRule) Restricts all later drawing to the inside of the path. Undo it with save()/restore().
isPointInPath(x, y), isPointInStroke(x, y) Hit tests against the current path (or a Path2D passed first). Useful for clicks on shapes.
new Path2D(svgPathData?) A reusable path object with the same path methods. It accepts SVG path syntax: new Path2D("M10 10 h80 v80 Z").

Text

Member Description
fillText(text, x, y, maxWidth?) Draws filled text. With maxWidth, the text is squeezed to fit.
strokeText(text, x, y, maxWidth?) Draws outlined text.
measureText(text) Returns a TextMetrics object: width, plus actualBoundingBoxLeft/Right/Ascent/Descent and font ascent/descent values.
font A CSS font shorthand string. Default "10px sans-serif".
textAlign "start" (default), "end", "left", "right", "center": which part of the text sits at x.
textBaseline "alphabetic" (default), "top", "hanging", "middle", "ideographic", "bottom": which line sits at y.
direction "inherit" (default), "ltr", "rtl".
letterSpacing, wordSpacing CSS lengths such as "2px". Newer: check support for older browsers.
fontKerning, fontStretch, fontVariantCaps, textRendering Finer font controls, matching the CSS properties of similar names.
textAlign, textBaseline and measureText

The exact width depends on the font your system uses for system-ui, so the number can differ between computers. That is why layouts that put text in boxes should always measure instead of guessing.

Images

Member Description
drawImage(img, dx, dy) Draws an image at its natural size. img can be an <img>, <video> (the current frame), another <canvas>, an ImageBitmap, an OffscreenCanvas or an SVG <image>.
drawImage(img, dx, dy, dw, dh) Draws it scaled into a box.
drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) Draws the part (sx, sy, sw, sh) of the source into the box (dx, dy, dw, dh): cropping, sprite sheets, zooming.
imageSmoothingEnabled true by default. Set false for crisp, blocky pixel art when scaling up.
imageSmoothingQuality "low" (default), "medium", "high".

The image must be loaded before you draw it: wait for its load event, or use await img.decode().

drawImage: whole, scaled and cropped

Transforms

Transforms change the coordinate system for everything drawn afterward. They accumulate: two rotate(0.1) calls rotate by 0.2.

Member Description
translate(x, y) Moves the origin.
rotate(angle) Rotates around the current origin (radians, clockwise).
scale(x, y) Scales; negative values mirror.
transform(a, b, c, d, e, f) Multiplies the current matrix by the given one.
setTransform(a, b, c, d, e, f) or setTransform(matrix) Replaces the current matrix.
resetTransform() Same as setTransform(1, 0, 0, 1, 0, 0).
getTransform() Returns the current matrix as a DOMMatrix.

State

Member Description
save() Pushes the current state onto a stack: styles, line settings, font and text settings, transform, clipping region, compositing, shadows, filter, smoothing. The path and the bitmap are not saved.
restore() Pops the last saved state.
reset() Clears the bitmap and resets every state and the path to the defaults (newer; resizing the canvas does the same in older browsers).
canvas The <canvas> element this context belongs to.
getContextAttributes() The options passed to getContext(), such as alpha and willReadFrequently.
Transforms with save and restore

Styles, lines and shadows

Member Description
fillStyle, strokeStyle A CSS color string, a CanvasGradient or a CanvasPattern. Default "#000000".
createLinearGradient(x0, y0, x1, y1) A gradient along a line; add colors with gradient.addColorStop(offset, color).
createRadialGradient(x0, y0, r0, x1, y1, r1) A gradient between two circles.
createConicGradient(angle, x, y) A gradient that sweeps around a point (color wheels, pie charts).
createPattern(image, repetition) A repeating image; repetition is "repeat", "repeat-x", "repeat-y" or "no-repeat".
lineWidth Line width in pixels, centered on the path. Default 1.
lineCap "butt" (default), "round", "square".
lineJoin "miter" (default), "round", "bevel".
miterLimit When long miters are cut off. Default 10.
setLineDash(segments), getLineDash() Dash pattern as an array, such as [8, 4]; [] for solid lines.
lineDashOffset Where the dash pattern starts.
shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY A drop shadow for everything drawn while they are set. The shadow is only drawn when shadowColor is not transparent and blur or offset is non-zero.
filter CSS filter functions as a string: "blur(4px) grayscale(1)". Applied to later drawing. Not available in older Safari versions.

Compositing

Member Description
globalAlpha Opacity (0โ€“1) applied to everything drawn. Default 1.
globalCompositeOperation How new pixels combine with existing ones. Default "source-over" (draw on top).

The values of globalCompositeOperation are the Porter-Duff operators source-over, source-in, source-out, source-atop, destination-over, destination-in, destination-out, destination-atop, lighter, copy and xor, and the CSS blend modes multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity.

globalCompositeOperation

Pixels

Member Description
getImageData(x, y, w, h) Copies pixels into an ImageData object. Its data is a Uint8ClampedArray with 4 bytes per pixel (red, green, blue, alpha, 0โ€“255), row by row.
putImageData(imageData, x, y) Writes pixels back. Ignores transforms, globalAlpha and compositing.
createImageData(w, h) A new, transparent ImageData to fill yourself.
getContext("2d", { willReadFrequently: true }) An option (not a member) that tells the browser you will call getImageData() often, so it keeps the bitmap in memory instead of on the GPU.

getImageData(), toDataURL() and toBlob() throw a SecurityError once the canvas is tainted: an image from another origin has been drawn on it without CORS approval. Drawing your own shapes never taints a canvas.

Grayscale with getImageData and putImageData

Usage notes

  • Always beginPath(). Forgetting it is the most common canvas bug: each fill() or stroke() redraws every subpath since the last beginPath(), so earlier shapes change color or get darker.
  • Crisp lines. A 1-pixel line at an integer coordinate straddles two pixel rows and looks blurry. Draw it at x + 0.5, or use even line widths.
  • High-density screens. Make the bitmap devicePixelRatio times bigger than the CSS size and call ctx.scale(ratio, ratio) once, as described on the <canvas> page.
  • Group state changes. Wrap temporary changes (a rotation, a clip, a shadow) in save() and restore() instead of undoing them by hand.
  • Animation. Clear and redraw the canvas in a requestAnimationFrame() callback; see Drawing and Animating with Canvas.
  • Accessibility. Pixels have no meaning to assistive technology. Put a text description in the canvas's fallback content and keep real controls as HTML.
  • Other contexts. getContext("webgl2") and getContext("webgpu") give 3D GPU APIs, which are entirely different; OffscreenCanvas offers the same 2D API inside a Web Worker.

Browser support

The 2D context is supported in every browser. Newer members, including roundRect(), reset(), createConicGradient(), letterSpacing/wordSpacing and filter, arrived in Safari later than in other browsers, so check support if you need older versions.