CodexBloom - Programming Q&A Platform

HTML `<canvas>` not rendering updates after resizing the window in Chrome

👀 Views: 226 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-28
html canvas javascript HTML

I'm deploying to production and I've searched everywhere and can't find a clear answer. I'm a bit lost with I'm stuck on something that should probably be simple. I'm working with the HTML `<canvas>` element to create a simple drawing application, and I've encountered an scenario where resizing the browser window seems to prevent the canvas from rendering any updates or drawings made after the resize event. Here's a simplified version of my code: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas Resize scenario</title> </head> <body> <canvas id="myCanvas" width="500" height="500" style="border:1px solid #000;"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'red'; ctx.fillRect(20, 20, 150, 100); window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; // Attempt to redraw ctx.fillStyle = 'red'; ctx.fillRect(20, 20, 150, 100); }); </script> </body> </html> ``` I notice that after resizing the window, the canvas appears blank despite calling the drawing functions again within the resize event. I have tried explicitly resetting the canvas' width and height properties, but no luck. My browser is the latest version of Chrome, and I'm unsure if this is a bug or if I'm missing something fundamental about how the canvas should work after a resize. I've checked for console errors but there are none. Any help would be greatly appreciated! I'm working on a web app that needs to handle this. I'm working with Html in a Docker container on macOS. Cheers for any assistance! I've been using Html for about a year now. What's the correct way to implement this? I appreciate any insights!