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> class Attribute

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

Classnames are defined in a stylesheet or in a local <style> element.

Classes, i.e. classnames, are used for styling the canvas 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

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

Multiple classnames are separated by a space.

JavaScript uses classes to access 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>

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