An id on a <canvas> tag assigns an identifier to the canvas.
The identifier must be unique across the page.
An id attribute on a <canvas>.
<canvas id="mycanvas" height="110" width="110">
</canvas>
<script>
( () => {
let canvas = document.getElementById("mycanvas");
let context = canvas.getContext("2d");
context.fillStyle = "lightblue";
context.fillRect(5, 5, 100, 100);
} )();
</script>
The id attribute assigns an identifier to the <canvas> element.
The id allows JavaScript to easily access the <canvas> element.
It is also used to point to a specific id selector in a style sheet.
Tip: id is a global attribute that can be applied to any HTML element.
<canvas id="identifier">
Value | Description |
---|---|
identifier | A unique alphanumeric string. The id value must begin with a letter ([aside-Zaside-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.). |
A <canvas> with a unique id.
Clicking the button draws a colored rectangle inside the canvas.
<canvas id="thecanvas" height="110" width="110">
</canvas><br/><br/>
<button onclick="draw();">Draw rectangle</button>
<script>
( () => {
let canvas = document.getElementById("thecanvas");
let context = canvas.getContext("2d");
context.fillStyle = "lightblue";
context.fillRect(5, 5, 100, 100);
} )();
let draw = () => {
let canvas = document.getElementById("thecanvas");
let context = canvas.getContext("2d");
context.fillStyle = "orangered";
context.fillRect(20, 20, 70, 70);
}
</script>
The id attribute assigns a unique identifier to the canvas.
Upon page load JavaScript uses the id to locate the canvas and draw a colored rectangle.
Clicking the button draws a smaller colored rectange.
Here is when id support started for each browser:
Chrome
|
4.0 | Jan 2010 |
Firefox
|
2.0 | Oct 2006 |
IE/Edge
|
9.0 | Mar 2011 |
Opera
|
9.0 | Jun 2006 |
Safari
|
3.1 | Mar 2008 |
Back to <canvas>