Canvas width and height in HTML5
Assign width
and height
attributes right inside the <canvas>
tag for static sizes:
In case of a responsive display, opt for JavaScript to configure your canvas size:
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:
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:
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:
Was this article helpful?