CodexBloom - Programming Q&A Platform

HTML <canvas> drawing implementation guide correctly when resizing the window on mobile devices

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
html canvas responsive-design HTML

I keep running into This might be a silly question, but I just started working with I'm sure I'm missing something obvious here, but I'm working with a question with an HTML `<canvas>` element where the drawing does not scale or update correctly when the browser window is resized on mobile devices..... I am using the following code to set up my canvas and draw a simple rectangle: ```html <canvas id="myCanvas" width="300" height="150"></canvas> <script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = '#FF0000'; ctx.fillRect(10, 10, 50, 50); </script> ``` The scenario arises when I resize the window. On desktop browsers, everything behaves as expected, but on mobile (specifically iOS Safari and Chrome), the rectangle appears stretched or not centered anymore. I tried adding a resize event listener to redraw the canvas: ```javascript window.addEventListener('resize', function() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx.fillStyle = '#FF0000'; ctx.fillRect(10, 10, 50, 50); }); ``` However, this seems to reset the canvas dimensions and results in a blank canvas after resizing. I've checked that I am not losing context, and I have also tried calling `ctx.clearRect()` before redrawing, but the scenario continues. Is there a proper way to handle resizing the `<canvas>` on mobile without losing the drawn content or causing distortion? Are there specific practices I should follow to maintain the aspect ratio and positioning of elements on the canvas? Any insights or solutions would be greatly appreciated! I'm working on a web app that needs to handle this. I appreciate any insights! I'm using Html stable in this project. Am I approaching this the right way? For reference, this is a production desktop app. This is for a web app running on CentOS.