Last demo left off with the drawing adjusting to the correct resolution every time that it’s drawn. But it was drawn manually with button clicks, and if the page size changed after drawing it stretched to the new size instead of staying sharp.
To work well on a responsive page, the canvas needs to update automatically when the window changes size. A resize event listener on the window object will suffice, but it fires repeatedly as the window size changes.
You can see this in action below. The number counts how many times the resize event occurs:
If the canvas is computationally expensive to draw, then it’s even more expensive to draw over and over as the window size changes. Better to let the image be upscaled until the resizing is done, then only redraw it once. A technique called “debouncing” will do just that.
The previous post covered adjusting the canvas size to match how large it’s being drawn on the web page. And if you’re reading on a computer with a 1080p screen or similar, it looked pretty good. But ever since the iPhone 4 and its “retina display” stepped up the pixel density much higher than historical norms, there’s one more piece of this pixelation puzzle.
When Apple subdivided every pixel on their screen into two rows and two columns, they couldn’t treat these like normal pixels any more - an object on screen defined as 10 pixels wide would be only half its intended size if it were displayed using 10 of these tiny new pixels.
Instead, they used multiple physical pixels to make up each pixel of size defined in CSS or HTML, giving objects the same size as before but allowing for sharper detail. In those first retina screens they used 2 hardware pixels for every 1 pixel of a web page layout. That 2:1 ratio is called the “device pixel ratio,” and it tells us that the width and height of the canvas both need to be doubled to display a sharp image on that screen. Newer screens with even higher pixel densities have driven that up even further with a 3:1 ratio.