In HTML, the <canvas> element is used for drawing graphics. Its size can be adjusted in various ways. It is crucial to differentiate between CSS styles and the actual drawing surface size of the canvas.
1. Directly setting in the HTML tag
You can specify the canvas size directly using the width and height attributes within the <canvas> tag. This sets the drawing surface size, not the visual display size controlled by CSS.
html<canvas id="myCanvas" width="300" height="200"></canvas>
In this example, the drawing surface is set to 300 pixels wide and 200 pixels high.
2. Using CSS to adjust size
Using CSS, you can adjust the canvas size, but this only affects the visual display size and does not alter the actual drawing surface size. If the CSS size does not match the drawing surface size, the graphics may become distorted due to stretching or compression.
html<style> #myCanvas { width: 300px; height: 200px; } </style> <canvas id="myCanvas"></canvas>
3. Using JavaScript to dynamically adjust size
In scenarios requiring dynamic adjustments based on window size or other conditions, JavaScript can be used to modify the canvas size. Ensure the drawing surface size matches the CSS size to prevent distortion.
javascriptconst canvas = document.getElementById('myCanvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight;
This code adjusts the drawing surface size to match the browser window dimensions.
Conclusion
When adjusting HTML canvas elements, setting both the CSS and the attributes' width and height ensures the display remains undistorted despite CSS stretching. For responsive design or dynamic environments, using JavaScript for dynamic size adjustment is typically the most flexible solution.