A data-* attribute on a <canvas> tag attaches additional data to the canvas.
To create a custom attribute, replace * with a lowercase string, such as data-id
, data-status
, or data-location
.
A custom data-pallete
attribute on a <canvas> element.
The attribute value is not visible, but is readable by JavaScript.
<canvas data-pallete="ocean"
id="canvas" width="120" height="120"></canvas>
<script>
( () => {
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
context.fillStyle = "steelblue";
context.fillRect(10, 10, 100, 100);
context.fillStyle = "cadetblue";
context.fillRect(35, 10, 25, 100);
context.fillStyle = "mediumturquoise";
context.fillRect(60, 10, 25, 100);
context.fillStyle = "paleturquoise";
context.fillRect(85, 10, 25, 100);
} )();
</script>
The data-* attribute adds custom information to a <canvas>
element.
The * part is replaced with a lowercase string, such as data-id, data-status, or data-location.
An <canvas>
element can have any number of data-* attributes, each with their own name.
Using data-* attributes reduces the need for requests to the server.
Note: The data-* attribute is not visible and does not change the appearance of the canvas.
<canvas data-*="value" >
Note: The * can be any string, such as data-id
, data-cost
, data-supplier
, etc.
Value | Description |
---|---|
value | A string value. Can be numeric, alphanumeric, JSON, etc. |
A custom data-palette
attribute on a <canvas>
element.
JavaScript reads the data-palette
value, which is 'fire', and then draws rectangles with a fire colored palette.
<canvas data-palette="fire"
id="mycanvas" width="120" height="120"></canvas>
<script>
( () => {
let canvas = document.getElementById("mycanvas");
let context = canvas.getContext("2d");
let palette = canvas.getAttribute('data-palette');
if (palette === "fire") {
context.fillStyle = "firebrick";
context.fillRect(10, 10, 100, 100);
context.fillStyle = "red";
context.fillRect(35, 10, 25, 100);
context.fillStyle = "orangered";
context.fillRect(60, 10, 25, 100);
context.fillStyle = "orange";
context.fillRect(85, 10, 25, 100);
} else if (palette === "ocean") {
context.fillStyle = "steelblue";
context.fillRect(10, 10, 100, 100);
context.fillStyle = "cadetblue";
context.fillRect(35, 10, 25, 100);
context.fillStyle = "mediumturquoise";
context.fillRect(60, 10, 25, 100);
context.fillStyle = "paleturquoise";
context.fillRect(85, 10, 25, 100);
}
} )();
</script>
The <canvas>
tag contains the data-palette
attribute.
The data-palette
attribute specifies the palette for drawing the canvas.
JavaScript draws the properly colored rectangles into the canvas element.
Here is when data-* 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>