HTML <canvas> width Attribute

The width attribute on a <canvas> tag sets the width of the canvas. The width is specified in pixels -- without the ‘px‘ unit.

Example

#

A width attribute on a <canvas> element.
The width attribute overrides the original canvas width. The border shows the outline.

<canvas id="mycanvas" height="120" width="120"
        style="border:1px solid #aaa;">
</canvas>

<script>

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

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

</script>

Using width

The width attribute specifies the width of the canvas.

The width is defined in pixels, without the 'px' unit.

To define the width in % or another unit, use the CSS width property.

The default width of a canvas is 300 pixels.


Syntax

<canvas width="pixels">

Values

#

Value Description
pixels A number (e.g. 300).

Browser support

Here is when width support started for each browser:

Chrome
4.0 Jan 2010
Firefox
2.0 Oct 2006
IE/Edge
9.0 Mar 2011
Opera
9.0 Oct 2005
Safari
3.1 Mar 2008

You may also like

 Back to <canvas>
Guides