HTML5 Canvas Not Resizing Properly on Window Resize Events in Chrome 117
After trying multiple solutions online, I still can't figure this out. I'm reviewing some code and I'm trying to figure out I'm working on a personal project and I'm working with an HTML5 `<canvas>` element that should resize dynamically when the window is resized. However, I'm running into issues where the canvas does not maintain its aspect ratio, and it results in distortion of the drawn content. I've set up a simple canvas and an event listener to handle the window resize: ```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 Example</title> </head> <body> <canvas id="myCanvas" width="800" height="400" style="border:1px solid #000;"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'blue'; ctx.fillRect(0, 0, 200, 100); function resizeCanvas() { const aspectRatio = canvas.width / canvas.height; canvas.width = window.innerWidth; canvas.height = window.innerWidth / aspectRatio; // Redraw the rectangle after resizing ctx.fillStyle = 'blue'; ctx.fillRect(0, 0, 200, 100); } window.addEventListener('resize', resizeCanvas); </script> </body> </html> ``` The `resizeCanvas` function updates the width and height based on the window's inner width, attempting to keep the original aspect ratio. However, when I resize the browser window, the canvas content appears squished or stretched, especially when I change the height. I've tried using `window.innerHeight` to adjust the height as well, but that leads to inconsistent behaviors depending on the resize direction. Is there a better way to handle canvas resizing while preserving the aspect ratio without losing the drawn content? Any tips or best practices would be appreciated. I'm testing this in Chrome 117, and I've confirmed that it doesn't happen in Firefox or Safari. I'm working on a API that needs to handle this. I'd really appreciate any guidance on this. I recently upgraded to Html LTS. I'd really appreciate any guidance on this. My team is using Html for this CLI tool.