HTML <canvas> class Attribute

The class attribute on a <canvas> tag assigns one or more classnames to the canvas element. Classes are used to style elements. Classnames are defined in a stylesheet or in a local <style> element.

Example

#

A class attribute styling a <canvas> element.

<style>
  .bordered {border:4px solid lightblue;}
</style>

<canvas class="bordered" id="mycanvas" 
        width="120" height="120"></canvas>

<script>

  ( () => {
    let canvas = document.getElementById("mycanvas");
    let context = canvas.getContext("2d");

    context.fillStyle = "paleturquoise";
    context.fillRect(10, 10, 100, 100);
  } )();

</script>

Using class

The class attribute assigns one or more classnames to the <canvas> tag.

Multiple classnames are separated by a space.

Classes (i.e. classnames) are used for styling the canvas element.

JavaScript uses classes to access one or more elements by classname.

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


Syntax

<canvas class="classnames" >

Values

#

Value Description
classnames One or more space-separated class names.

More Examples

A class attribute styling a <canvas> element.
Every second, JavaScript toggles a classname that changes the border color.

<style>
  .bordered {border:4px solid lightblue;}
  .border-red { border-color: orangered; }
</style>

<canvas class="bordered" id="canvas" 
        width="120" height="120"></canvas>

<script>

  ( () => {

    let canvas = document.getElementById("canvas");
    let context = canvas.getContext("2d");

    context.fillStyle = "paleturquoise";
    context.fillRect(10, 10, 100, 100);

    setInterval( () => {
        canvas.classList.toggle("border-red");
    }, 1000)

  } )();

</script>


Code explanation

Two CSS classes are defined in the <style> element.

The class attribute in <canvas> is assigned one classname.

Once every second, JavaScript toggles another class, creating the impression of a flashing border.

JavaScript uses an anonymous, self-executing lambda expression to get the process started.


Browser support

Here is when class 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