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.
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>
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.
<canvas class="classnames" >
Value | Description |
---|---|
classnames | One or more space-separated class names. |
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>
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.
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 |
Back to <canvas>