CodexBloom - Programming Q&A Platform

HTML `<canvas>` size not matching CSS dimensions in Chrome 95

πŸ‘€ Views: 1305 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
html canvas css chrome HTML

I'm relatively new to this, so bear with me. I'm stuck on something that should probably be simple. I tried several approaches but none seem to work. I'm prototyping a solution and I've been struggling with this for a few days now and could really use some help. Hey everyone, I'm running into an issue that's driving me crazy... I'm having an issue where the dimensions of my `<canvas>` element aren't matching the CSS styles I've applied in Chrome 95. I've set the canvas size using both the HTML attributes and CSS, but they don't seem to align as expected. Here’s the code snippet: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas Size Issue</title> <style> canvas { width: 100%; height: 400px; border: 1px solid black; } </style> </head> <body> <canvas id="myCanvas" width="800" height="400"></canvas> <script> const canvas = document.getElementById('myCanvas'); const context = canvas.getContext('2d'); context.fillStyle = 'green'; context.fillRect(0, 0, canvas.width, canvas.height); </script> </body> </html> ``` In this setup, I expect the canvas to visually fit the dimensions defined by the CSS, but it appears to be stretching and not maintaining the intended proportions. Inspecting with Chrome DevTools shows that the computed width is 800px instead of filling the parent container as expected. I tried removing the `width` and `height` attributes from the `<canvas>` tag, but then the canvas doesn't render anything because its default size is too small. I also attempted to use `window.onload` to resize the canvas, but that didn’t solve the rendering issue either. This behavior is consistent only on Chrome; Firefox and Edge seem to handle it correctly. What am I missing here? Is there a specific best practice for handling `<canvas>` sizing that I should follow to ensure compatibility across browsers? Any insights or workarounds would be appreciated! For context: I'm using Html on macOS. Any help would be greatly appreciated! This is part of a larger CLI tool I'm building. Any suggestions would be helpful. Thanks, I really appreciate it! I'm working on a CLI tool that needs to handle this.