Dofactory.com
Dofactory.com
Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

HTML <canvas> id Attribute

An id on a <canvas> tag assigns an identifier to the canvas.

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


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>

Last updated on Sep 30, 2023

Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

Guides