How to use the HTML <canvas> tag element

The <canvas> element in HTMLHypertext Markup Language is used to draw animations and graphics via scripts (mostly JavaScript). It can use either the WebGL APIApplication Programming Interface or the canvas scripting API.

The canvas tag also supports the Event Attributes and Global Attributes in HTML.

Attributes

Here are some frequently useful attributes for the canvas tag:

Attribute Value Description
Width Pixels Indicates the width of canvas with default value = 300
Height Pixels Indicates the height of canvas with default value = 150

Syntax


<canvas attribute1 attribute2>
   content to show what canvas displays.
</canvas>

Supported browsers

Below are some supported browsers with the versions in which they started to support the <canvas> element for graphics/animation drawing in HTML.

Code

The following code snippet illustrates the functionality of the <canvas> element at line 6.

The <script> tags help generate graphics with the canvas placeholder as Browser does not support the <canvas> tag.

canvx.fillStyle sets color and canvx.fillRect sets dimensions on line 10 and line 11, respectively.

Free Resources