HTML <canvas> Not Rendering Properly on Mobile Devices - implementing High DPI Screens
I'm confused about I tried several approaches but none seem to work. I'm relatively new to this, so bear with me. I'm refactoring my project and I'm writing unit tests and I'm sure I'm missing something obvious here, but I’m developing a simple drawing application using the HTML <canvas> element, and I’m working with issues when testing on high DPI mobile devices like the iPhone. The drawings look pixelated and don’t seem to scale properly. I’ve set my canvas dimensions explicitly in CSS, but the rendered output is still blurry. Here’s the code I’m using for my canvas setup: ```html <canvas id="myCanvas" width="800" height="600"></canvas> <style> canvas { border: 1px solid black; width: 100%; height: auto; } </style> ``` In addition, my drawing function looks like this: ```javascript const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); function draw() { ctx.fillStyle = 'red'; ctx.fillRect(0, 0, 150, 75); } draw(); ``` When I view this on my Mac or desktop, it appears just fine, but on an iPhone, the rectangle appears jagged and not sharp at all. I suspect it has something to do with the device's pixel density, but I'm unsure about how to handle this correctly. I’ve tried adjusting the canvas size dynamically based on the window's device pixel ratio like this: ```javascript const dpr = window.devicePixelRatio || 1; canvas.width = 800 * dpr; canvas.height = 600 * dpr; ctx.scale(dpr, dpr); ``` Yet, I still see no improvement. I need some guidance on how to ensure that my canvas renders crisply on high DPI screens without losing the aspect ratio or creating layout issues. Any insights or best practices would be greatly appreciated! I appreciate any insights! This is part of a larger microservice I'm building. Am I approaching this the right way? For context: I'm using Javascript on macOS. What would be the recommended way to handle this? I'm using Javascript 3.11 in this project. I'm using Javascript 3.9 in this project. I'm coming from a different tech stack and learning Javascript.