HTML <canvas> width attribute

Definition and Usage

width The width attribute specifies the width of the <canvas> element in pixels.

Tip

Use height attribute Specify the height of the <canvas> element in pixels.

When the height or width of the canvas is reset, the content of the canvas will be cleared (see the example at the bottom of the page).

Please visit our HTML Canvas Tutorial Learn more about the <canvas> element in our

Instance

Example 1

A <canvas> element with both height and width set to 200 pixels:

<canvas id="myCanvas" width="400" height="400" style="border:1px solid">

Try It Yourself

Example 2

By setting the width attribute to 400px, clear the canvas (using JavaScript):

<canvas id="myCanvas" width="200" height="200" style="border:1px solid"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#0192B9";
ctx.fillRect(50, 50, 300, 300);
function clearCanvas() {
  c.width = 400;
}
</script>

Try It Yourself

Syntax

<canvas width="pixels">

Attribute Value

Value Description
pixels Specifies the width of the canvas in pixels (for example, “100”). The default value is 300.

Browser Support

The numbers in the table indicate the first browser version to fully support this attribute.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 2.0 3.1 9.0