CodexBloom - Programming Q&A Platform

HTML `<canvas>` Not Rendering Correctly on Safari - Blurry Output with Multiple Resizes

👀 Views: 17 💬 Answers: 1 📅 Created: 2025-06-12
html canvas safari JavaScript

I've been researching this but I'm experiencing an issue with the `<canvas>` element in my HTML5 application. When resizing the canvas multiple times, the rendered output becomes blurry, especially in Safari (version 16.0). I’ve set the canvas dimensions using JavaScript, but the drawing quality deteriorates significantly after a few resizes. Here’s a snippet of the code I’m using: ```javascript const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); function setCanvasSize(width, height) { canvas.width = width; canvas.height = height; draw(); } function draw() { ctx.fillStyle = 'blue'; ctx.fillRect(10, 10, 150, 100); } setCanvasSize(300, 200); // Resizing logic setCanvasSize(600, 400); setCanvasSize(300, 200); ``` I’ve tried resetting the `canvas.width` and `canvas.height` each time I resize, and I also verified that nothing is being cached incorrectly. However, after resizing back to the original dimensions, the output is noticeably less sharp. In Chrome and Firefox, it works fine, which makes me suspect a Safari-specific rendering issue. Additionally, I’ve explored using `window.devicePixelRatio` to adjust the canvas scaling, but that approach doesn’t seem to resolve the blurriness. Here’s how I attempted that: ```javascript function setCanvasSize(width, height) { const ratio = window.devicePixelRatio || 1; canvas.width = width * ratio; canvas.height = height * ratio; ctx.scale(ratio, ratio); draw(); } ``` Unfortunately, this only made the canvas proportionally larger but didn’t improve the rendering quality. Has anyone else faced this issue with Safari? Is there a specific configuration or workaround that can help maintain the canvas drawing clarity during resizes? Could this be a known issue?