CKTIS / JavaScript
Canvas 2D: transforms, rectangles, and paths
Keep the transform, the pixels, and the default path separate. Learn when coordinates are transformed, which calls change pixels immediately, and what remains after `stroke()`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
ctx.setTransform(a, b, c, d, e, f)
ctx.setTransform(matrix)
ctx.setTransform()
ctx.clearRect(x, y, width, height)
ctx.fillRect(x, y, width, height)
ctx.beginPath()
ctx.moveTo(x, y)
ctx.lineTo(x, y)
ctx.stroke()
ctx.stroke(path)The methods grouped under CanvasRenderingContext2D.setTransform/clearRect/fillRect/beginPath/moveTo/lineTo/stroke belong to a Web API, not ECMAScript 2024. Call them on the context ctx returned by canvas.getContext('2d'), which may return null. Support for individual call forms depends on the runtime. All seven methods return undefined on a normal call.
setTransform(a, b, c, d, e, f) replaces the current matrix, unlike transform(), which multiplies it. It maps (x, y) to (a*x + c*y + e, b*x + d*y + f). The object overload takes a 2D matrix dictionary (DOMMatrix2DInit): omitted components default to identity values, and conflicting aliases such as a and m11 throw TypeError. The standard allows a zero-argument call to set the identity matrix. In the six-number overload, any argument that is NaN or infinite leaves the current matrix unchanged. The dictionary overload constructs a DOMMatrix from a valid dictionary and assigns it as the current matrix without that check.
fillRect(x, y, width, height) immediately paints a rectangle using fillStyle. With the same parameters, clearRect() clears pixels to transparent black (opaque black with alpha: false), regardless of paint style, globalAlpha, or compositing mode. Both use the current transform and clipping region and leave the path alone. A zero dimension does nothing; a negative dimension extends the rectangle in the opposite direction from (x, y).
beginPath() empties the default path without erasing pixels. moveTo(x, y) starts a new subpath without connecting it to the previous one. lineTo(x, y) adds a straight segment from the last point; if no subpath exists, it only sets the starting point. None of these three methods paints. moveTo(), lineTo(), and both rectangle methods ignore calls with NaN or infinite coordinates or dimensions.
stroke() paints the current default path with strokeStyle and line settings such as lineWidth. It neither closes open subpaths nor empties the path. Default-path coordinates are transformed when added, not again when stroked, although the transform at stroke time still affects the stroke itself, for example its thickness. With stroke(path), the geometry of the supplied Path2D is transformed at paint time without modifying the object. save() and restore() preserve and restore drawing state such as the matrix, but not the default path or pixels.
Examples
<!doctype html>
<meta charset="utf-8">
<title>Canvas 2D</title>
<canvas id="demo" width="32" height="24" hidden></canvas>
<script>
(() => {
const canvas = document.getElementById('demo');
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas 2D is unavailable');
ctx.setTransform(1, 0, 0, 1, 8, 4);
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, 16, 8);
ctx.beginPath();
ctx.moveTo(2, 12);
ctx.lineTo(14, 12);
ctx.clearRect(0, 0, 4, 8);
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.strokeStyle = '#000';
ctx.lineWidth = 4;
ctx.stroke();
const alphaAt = (x, y) => ctx.getImageData(x, y, 1, 1).data[3];
console.log([alphaAt(9, 6), alphaAt(15, 6), alphaAt(15, 16), alphaAt(5, 12)].join(', '));
})();
</script>Result
0, 255, 255, 0
Save the example as an HTML file, open it in a browser, and check the browser console. The expected alpha values `0, 255, 255, 0` correspond to the cleared area, the remaining fill, the translated line, and an untouched spot in the untranslated coordinate system. `getImageData()` reads bitmap coordinates; privacy settings may alter the result, and reading a canvas tainted by unauthorized cross-origin content can throw `SecurityError`.
Related lessons
- JavaScript · Lesson 34 · Advanced · Version: 4
Sources
- HTML Standard — The canvas settings
- HTML Standard — The canvas state
- HTML Standard — Building paths
- HTML Standard — Transformations
- HTML Standard — Drawing rectangles to the bitmap
- HTML Standard — Drawing paths to the canvas
- CanvasRenderingContext2D: setTransform() method
- CanvasRenderingContext2D: getImageData() method