CKTIS / JavaScript
HTMLCanvasElement: rendering contexts and bitmap dimensions
Choose a rendering context with `getContext()` and size its bitmap with `width` and `height`. Unlike CSS sizing, writing either dimension clears the bitmap and resets drawing state in 2D mode.
Version: Current web platform; runtime support varies
Syntax
canvas.getContext(contextId)
canvas.getContext(contextId, options)
canvas.width
canvas.height
canvas.width = bitmapWidth
canvas.height = bitmapHeightThe HTML Standard defines the <canvas> element’s HTMLCanvasElement interface, including the getContext() method and the two properties width and height. These are Web APIs; ECMAScript 2024 neither defines them nor establishes their browser support. canvas.getContext(contextId, options) takes a string ID and optional mode-specific settings. "2d" selects CanvasRenderingContext2D, "bitmaprenderer" selects ImageBitmapRenderingContext, "webgl" selects WebGLRenderingContext, "webgl2" selects WebGL2RenderingContext, and "webgpu" selects GPUCanvasContext. Mode and option availability depend on the runtime.
The first successful call fixes the element's mode. Calling again with the same ID returns the same object without applying new settings. An unsupported or unavailable mode, or a request for a different mode, returns null. After a successful transferControlToOffscreen(), the element is a placeholder: calling getContext() or assigning to width or height throws InvalidStateError.
canvas.width and canvas.height reflect the HTML attributes of the same names. They specify the bitmap's width and height as non-negative integers; a missing attribute or a parse failure gives the respective default of 300 or 150. Setting only canvas.style.width or canvas.style.height changes display size, not bitmap resolution; scaling can blur the image.
In 2D mode, assigning either dimension, even to its current value, clears the bitmap and resets drawing state, including the current path, transform, and styles, without replacing the context object. Set dimensions before drawing; after a resize, reapply the state you need and redraw. Do not assume the same reset behavior in other modes.
Drawing a cross-origin image without appropriate CORS permission can make the bitmap no longer origin-clean. Then getImageData() throws SecurityError; resizing a 2D bitmap discards its contents rather than exposing the blocked pixels.
Examples
<!doctype html>
<meta charset="utf-8">
<title>Canvas 2D resize reset</title>
<script>
(() => {
const canvas = document.createElement("canvas");
console.log(`${canvas.width}x${canvas.height}`);
canvas.width = 4;
canvas.height = 3;
console.log(`${canvas.width}x${canvas.height}`);
const ctx = canvas.getContext("2d");
if (ctx === null) throw new Error("2D canvas context unavailable");
ctx.fillRect(0, 0, 1, 1);
ctx.globalAlpha = 0.5;
const alphaAtOrigin = () => ctx.getImageData(0, 0, 1, 1).data[3];
console.log(`${alphaAtOrigin()} ${ctx.globalAlpha}`);
canvas.width = canvas.width;
console.log(`${alphaAtOrigin()} ${ctx.globalAlpha}`);
console.log(canvas.getContext("2d") === ctx);
console.log(canvas.getContext("bitmaprenderer") === null);
})();
</script>Result
300x150 4x3 255 0.5 0 1 true true
Save the example as an HTML file, open it in a browser, and read the output in the developer console. The first two lines show the dimensions. Assigning the same width changes pixel alpha from `255` to `0` and restores `globalAlpha` from `0.5` to `1`. The two `true` results show that the same context is kept and a different mode is rejected.
Related lessons
- JavaScript · Lesson 12 · Advanced · Version: 4
- JavaScript · Lesson 33 · Advanced · Version: 4
- JavaScript · Lesson 34 · Advanced · Version: 4