HTML <canvas> style Attribute

The style attribute on a <canvas> tag assigns a unique style to the canvas element. A style contains one or more CSS property/value pairs that define the appearance of the canvas.

Example

#

A style attribute on a <canvas> element.

<canvas id="mycanvas" width="220" height="110"
        style="border:1px dashed orangered;">
</canvas>

<script>
 
  ( () => {

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

    context.fillStyle = "lightblue";
    context.fillRect(5, 5, 210, 100);

  } )();

</script>

Using style

The style attribute specifies the style, i.e. look and feel, of the <canvas> element.

A style contains any number of CSS property/value pairs, separated by semicolons (;).

The style attribute overrides any other style that was defined in a <style> tag or an external CSS file.

This inline styling affects the current <canvas> element only.


Syntax

<canvas style="CSS-styles" >

Values

#

Value Description
CSS-styles One or more CSS property/value pairs separated by semicolons (;).

More Examples

A style attribute on a <canvas> element.
JavaScript looping through 5 border width increments.

<canvas id="canvas" width="220" height="110"
        style="border:1px dashed orangered;">
</canvas>

<script>
 
  ( () => {

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

    context.fillStyle = "lightblue";
    context.fillRect(5, 5, 210, 100);

    setInterval( () => {
        let width = canvas.style.borderWidth.replace('px', '');
        canvas.style.borderWidth = (width % 5 + 1) + "px";
    }, 500)

  } )();

</script>

Code explanation

The style attribute assigns a colored dashed border to the <canvas> element.

JavaScript reads the width, increments it by 1, and then reassigns the new value.

New values are not allowed to exceed 5px. Notice the entire page continually adjusting to this new width.


Browser support

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