Explain Codes LogoExplain Codes Logo

Canvas width and height in HTML5

html
responsive-design
canvas
javascript
Anton ShumikhinbyAnton Shumikhin·Sep 11, 2024
TLDR

Assign width and height attributes right inside the <canvas> tag for static sizes:

<canvas id="myCanvas" width="200" height="100"></canvas>

In case of a responsive display, opt for JavaScript to configure your canvas size:

var canvas = document.getElementById('myCanvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight;

Make sure you're not using CSS for dimension control, since this can lead to graphic distortion. The CSS deals with the scaling of the canvas drawing, not the canvas element itself.

Handling canvas size with JavaScript

The getContext('2d') method is your passport to the 2D rendering context of your canvas. Any change in canvas size clues a redraw. So, incorporate a mechanism in your code that caters to this:

function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; // Redraw please, let's not serve stale visuals. redraw(); } window.addEventListener('resize', resizeCanvas);

No one likes a squished or blown out of proportion element, right?

The CSS way of scaling vs. JavaScript sizing

CSS is great, but not when it comes to handling the canvas size. CSS sizing extends to how the canvas appears, not its actual drawing area, which can cause blurred lines and dimensions distortion. So let's leave the CSS out of our sizing equation.

Catering to redraws and clean-ups

Complex graphics and animations? Consider redraws and clean-ups. Use context.clearRect(0, 0, canvas.width, canvas.height) to wipe the slate clean before each redraw. No overlaps or ghosting, just a fresh new canvas:

function redraw() { var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); // ETCH-A-SKETCH mood, anyone? }

Living on the edge: Resolution and pixel density

High dots per inch (DPI) screens can descend into an artists' nightmare with blurred lines and low-quality outcomes. Adjust the canvas.width and canvas.height to your device’s pixel ratio for the intended dimensions:

var scale = window.devicePixelRatio; // Desired pixel density, locked and loaded. canvas.width = Math.floor(scale * intendedWidth); canvas.height = Math.floor(scale * intendedHeight); // CSS takes charge now. Stand back everyone. canvas.style.width = intendedWidth + "px"; canvas.style.height = intendedHeight + "px";