HTML5 `<canvas>` Not Rendering Images with High DPI on Retina Displays
I'm reviewing some code and Hey everyone, I'm running into an issue that's driving me crazy. I am working with an scenario with rendering images on an HTML5 `<canvas>` element for high-DPI displays, specifically Retina displays. My application uses a canvas of size 300x150 pixels, but when I attempt to draw an image to it, the image appears blurry or pixelated on these screens. I am loading the image and drawing it like this: ```javascript const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.src = 'path/to/image.png'; img.onload = function() { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); }; ``` I set the width and height attributes directly in the HTML as follows: ```html <canvas id="myCanvas" width="300" height="150"></canvas> ``` However, on Retina displays, the output is not sharp. I’ve read that I might need to adjust the canvas for the device pixel ratio, but I am unsure how to properly implement that. I tried scaling the canvas like this: ```javascript const dpr = window.devicePixelRatio || 1; canvas.width = 300 * dpr; canvas.height = 150 * dpr; ctx.scale(dpr, dpr); ``` But this seems to distort the image. The image still looks pixelated and I see the following warning in the console: `Image size exceeds canvas dimensions.` I've double-checked the source image dimensions, and they are 600x300 pixels. Can anyone guide me on correctly rendering a high-DPI canvas without losing image quality? Any tips on best practices for handling images in `<canvas>` would be greatly appreciated. My development environment is macOS. I'd really appreciate any guidance on this. This issue appeared after updating to Javascript 3.9. What are your experiences with this?