CodexBloom - Programming Q&A Platform

HTML <canvas> drawing not persisting on window resize in Chrome

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
canvas html5 resize chrome HTML

I need some guidance on I'm experiencing an scenario where my drawings on an HTML `<canvas>` element vanish when I resize the browser window in Chrome. I'm using a simple implementation to draw some shapes on the canvas, but it seems like the drawing context is lost on resize. Here’s the relevant part of my code: ```html <canvas id="myCanvas" width="500" height="500" style="border:1px solid #000;"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); function drawShapes() { ctx.fillStyle = 'blue'; ctx.fillRect(20, 20, 150, 100); } drawShapes(); window.addEventListener('resize', () => { // Why does this clear the canvas? ctx.clearRect(0, 0, canvas.width, canvas.height); }); </script> ``` I initially thought that I could just redraw the shapes in the `resize` event listener, but that leads to flicker and performance optimization, especially when redrawing complex shapes. I also tried saving the drawing data in an array and redrawing on resize, but it still results in a noticeable delay. The shapes are not complex, but I want to maintain smoothness and performance. Is there a recommended way to handle canvas drawings that don’t disappear during window resize? I'm using Chrome Version 117.0.5938.92. Any insights would be appreciated. Any feedback is welcome!