CKTIS / JavaScript
Canvas 2D: transforms, drawing state, clipping, and rectangles
Separate drawing state from the current path and bitmap so you can limit clipping to one drawing operation and clear only the intended pixels.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
ctx.setTransform(a, b, c, d, e, f)
ctx.setTransform()
ctx.setTransform(matrix2D)
ctx.save()
ctx.restore()
ctx.beginPath()
ctx.rect(x, y, width, height)
ctx.clip()
ctx.clip(fillRule)
ctx.clip(path)
ctx.clip(path, fillRule)
ctx.clearRect(x, y, width, height)
ctx.fillRect(x, y, width, height)
ctx.strokeRect(x, y, width, height)The methods in CanvasRenderingContext2D.setTransform/save/restore/beginPath/rect/clip/clearRect/fillRect/strokeRect belong to the web platform, not ECMAScript 2024. Support varies by runtime. setTransform(a, b, c, d, e, f) replaces the matrix rather than multiplying it: (x, y) maps to (a*x + c*y + e, b*x + d*y + f). It also accepts a DOMMatrix2DInit object: a and d default to 1, the others to 0, so calling it with no arguments sets the identity matrix. Conflicting values for synonymous keys, such as a and m11, throw TypeError. The six-number form leaves the matrix unchanged if any argument is infinite or NaN.
save() pushes a copy of the drawing state, including the transform, clip, and styles. restore() pops and reapplies the latest saved state; it does nothing on an empty stack. Neither the current path nor the pixels are saved. beginPath() empties the current path without changing the clip or bitmap. rect(x, y, width, height) adds a closed rectangular subpath without painting pixels. The transform applies to that path's geometry as it is built.
clip() replaces the clipping region with its intersection with the interior of the current path or a supplied Path2D. For Path2D, the transform applies when clip() is called, without modifying the object. The optional fill rule 'nonzero' (default) tests for a nonzero signed crossing count; 'evenodd' tests for an odd crossing count. clip() paints nothing, and repeated calls cannot expand the region. Save before clipping and restore after drawing: setting the identity transform does not remove the clip.
fillRect() fills using fillStyle; strokeRect() outlines using strokeStyle and the line settings; clearRect() erases to transparent black (opaque black with alpha: false), ignoring shadows, global alpha, and compositing. All three act directly on the bitmap, respect the transform and clip, and leave the path unchanged. So fillRect() does not supply geometry to clip(). clearRect() does not lift readback restrictions on a bitmap tainted by cross-origin data: getImageData() still throws SecurityError.
Examples
<!doctype html>
<meta charset="utf-8">
<title>Canvas 2D clipping</title>
<canvas id="canvas" width="20" height="12"></canvas>
<script>
(() => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d', { alpha: true });
if (!ctx) throw new Error('Canvas 2D unavailable');
ctx.fillRect(0, 0, 12, 12);
ctx.save();
try {
ctx.setTransform(1, 0, 0, 1, 4, 2);
ctx.beginPath();
ctx.rect(0, 0, 8, 8);
ctx.clip();
ctx.clearRect(-2, 2, 6, 4);
} finally {
ctx.restore();
}
ctx.lineWidth = 2;
ctx.strokeRect(14, 2, 4, 8);
const alphaAt = (x, y) => ctx.getImageData(x, y, 1, 1).data[3];
console.log([3, 5, 9, 14, 16].map(x => alphaAt(x, 5)).join(', '));
})();
</script>Result
255, 0, 255, 255, 0
Save the example as an HTML file, open it in a browser, and check the developer console. In order, the five alpha values show fill protected by the clip, a cleared pixel, untouched fill, the outline drawn after restoring state, and the transparent interior of that outline.
Related lessons
- JavaScript · Lesson 12 · Advanced · Version: 4
Sources
- HTML Standard — The canvas state
- HTML Standard — Transformations
- HTML Standard — Drawing rectangles to the bitmap
- HTML Standard — Drawing paths to the canvas
- HTML Standard — The canvas settings
- CanvasRenderingContext2D: setTransform() method
- CanvasRenderingContext2D: rect() method
- CanvasRenderingContext2D: getImageData() method