CKTIS / JavaScript
HTMLCanvasElement: bitmap width and height
`canvas.width` and `canvas.height` size the bitmap, not the CSS display box. With a 2D context, even assigning the current value clears the drawing and resets the drawing state.
Version: Current web platform; runtime support varies
Syntax
canvas.width
canvas.height
canvas.width = widthInPixels;
canvas.height = heightInPixels;HTMLCanvasElement.width and HTMLCanvasElement.height are read/write properties on a canvas element. They reflect the HTML attributes of the same names and set the bitmap's width and height in pixels. Write HTML attribute values as non-negative integers. If an attribute is missing or cannot be parsed as one, the default is 300 for width or 150 for height. These are web platform APIs, not ECMAScript features.
canvas.style.width and canvas.style.height set the element's size in page layout, not the bitmap dimensions. Changing CSS alone leaves the pixels and drawing intact. The displayed image can look blurry when enlarged or distorted when stretched to a different aspect ratio.
With a 2d context, assigning either bitmap dimension clears the drawing and resets the same context to its defaults, even if you assign the current value. The reset includes the current path, transform, and styles. Set dimensions before drawing; if you resize later, reapply the state you need and redraw.
Do not assume WebGL or WebGPU resets the same way as 2d. After transferControlToOffscreen(), the element is a placeholder: assigning to its width or height throws InvalidStateError. Set the dimensions on the OffscreenCanvas instead.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Canvas bitmap dimensions</title>
</head>
<body>
<script>
(() => {
const canvas = document.createElement('canvas');
console.log(`Default: ${canvas.width} × ${canvas.height}`);
canvas.width = 4;
canvas.height = 2;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas 2D is unavailable.');
ctx.fillRect(0, 0, 1, 1);
ctx.globalAlpha = 0.5;
const pixelAlpha = () => ctx.getImageData(0, 0, 1, 1).data[3];
canvas.style.width = '40px';
canvas.style.height = '20px';
console.log(`After CSS: ${canvas.width} × ${canvas.height}; pixel alpha ${pixelAlpha()}; globalAlpha ${ctx.globalAlpha}`);
canvas.width = canvas.width;
console.log(`After assignment: ${canvas.width} × ${canvas.height}; pixel alpha ${pixelAlpha()}; globalAlpha ${ctx.globalAlpha}`);
})();
</script>
</body>
</html>Result
Default: 300 × 150 After CSS: 4 × 2; pixel alpha 255; globalAlpha 0.5 After assignment: 4 × 2; pixel alpha 0; globalAlpha 1
Open the HTML file in a browser and read the output in the developer console. The canvas is not added to the page. The CSS change leaves the pixel opaque (`255`); assigning the same width clears it (`0`) and returns `globalAlpha` to `1`.
Related lessons
- JavaScript · Lesson 26 · Intermediate · Version: 3
- JavaScript · Lesson 27 · Intermediate · Version: 3