HTML <canvas> id Attribute

The id attribute on a <canvas> tag assigns an identifier to the canvas element. The identifier must be unique across the page.

Example

#

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>

Using id

The id attribute assigns an identifier to the <canvas> element.

The identifier must be unique across the page.

The id allows programmatic access to the <canvas> element.

Tip:  id is a global attribute that can be applied to any HTML element.


Syntax

<canvas id="identifier">

Values

#

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 (.).

More Examples

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>

Code explanation

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.


Browser support

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

You may also like

 Back to <canvas>
Guides