canvas element

If you don't know what an element is or how you must use it, I recommend you read the "HTML tags and attributes" tutorial that you can find in the HTML tutorials section.

Description

The canvas element creates a rectangular area where authors can render graphics and animations programatically and on the fly. This is a valuable resource when designing websites rich in animations and interactivity, or when developing on-page applications and videogames.

From a content author's view, the canvas element defines only a rectangular region. Its benefits become tangible when used together with a client-side programming language like Javascript.

Authors are encouraged to provide fallback alternatives to the contents displayed with the canvas element. These alternatives should be placed inside the element's tags, allowing browsers to hide them when the support for canvas is present.

Examples

The following example shows a canvas element running an animation carried out by a function written in Javascript. As the width and height of this element can't be a relative value (like a percentage), this function will also set, programatically, the width of the element so it takes all the space available in its parent.

<canvas id="canvas1" height="100"></canvas>

Now a canvas element will be set to provide some interactivity, by allowing the user to draw lines with the mouse pointer. You can test this drawing board by moving the mouse over the canvas while the left click is pressed. If you right-click over the element, the board will be cleared.

<canvas id="canvas2" height="200"></canvas>

Attributes

Specific attributes

width

The number of pixels to use as the width of the rectangle defined by this element. When this attribute isn't specified, the element's area takes a width of 300 pixels.

Example

<canvas width="500"></canvas>

height

The number of pixels to use as the height of the rectangle defined by this the element. When this attribute isn't specified, the element's area takes a height of 150 pixels.

Example

<canvas height="200"></canvas>

Global attributes

For information about global attributes refer to this list of global attributes in HTML5.

Events

Global events

For information about global events refer to this list of global events in HTML5.

X

Are you looking for a place to host your next website? I can help you with that!