The <canvas> tag is used to draw graphics, animations, or other dynamic visual content using JavaScript.
It is often used to create interactive visualizations or online games.
Structure and syntax of the <canvas> tag
Basic structure and syntax
Here is the basic syntax of a <canvas> tag:
<canvas id="monCanvas" width="500" height="300">
Your browser does not support this tag.
</canvas>In this example, the content between the <canvas> tags is displayed uniquely if the browser does not support this tag.
Usage example
As a more illustrative example, here is an example of using it with JavaScript:
<canvas id="monCanvas" width="500" height="300">
Your browser does not support the <canvas> tag.
</canvas>
<script>
const canvas = document.getElementById('monCanvas');
const context = canvas.getContext('2d');
context.fillStyle = 'blue';
context.fillRect(50, 50, 200, 100); // Draw a blue rectangle
</script>In this example, the <canvas> tag creates a drawing area that is 500 pixels wide and 300 pixels high.
The text id="monCanvas" gives a name to this area so that it can be retrieved with JavaScript. If the browser does not understand <canvas>, an alternative text is displayed instead.
With JavaScript, we retrieve the area with document.getElementById and activate the 2D drawing mode with getContext('2d').
Then, we choose the color blue with fillStyle, and draw a rectangle with fillRect(50, 50, 200, 100), which places a blue rectangle with:
- 200 pixels wide;
- 100 pixels high;
- and 50 pixels from the top and left.
In the end, we see a blue rectangle in the drawing area.
Attributes
The <canvas> tag accepts the following attributes:
width: Defines the width of the canvas in pixels.height: Defines the height of the canvas in pixels.
If these attributes are not specified, the default size is 300 pixels wide and 150 pixels high.
Best practices
Always use a unique identifier with the <canvas> tag to easily access it with JavaScript.
Prefer defining the dimensions of the canvas directly via the attributes width and height, rather than in the CSS style to have better precision in the drawings you will add.
Finally, always add an alternative content between the <canvas> tags for users whose browsers do not support this functionality. 😉
Difference with other similar tags
The <canvas> tag is often compared to <svg>, another tag that might seem to have similar functionalities... but quite the opposite!
Unlike <canvas>, the <svg> tag is used to draw vector graphics that remain editable after their creation.
Browser compatibility
The <canvas> tag is supported by all modern browsers.
| Browser | Compatibility |
|---|---|
| Chrome | Yes |
| Firefox | Yes |
| Safari | Yes |
| Edge | Yes |
| Internet Explorer | Partial (IE 9+) |