HTML5 <canvas> Tag

The HTML <canvas> tag can be used with the canvas scripting API to draw graphics and animations.

Both the starting and ending tag are required for this element. The parent of the <canvas> tag can be any element that accepts phrasing content.

You may (and should) provide alternate content inside the <canvas> block. This content will be rendered both on older browsers that don’t support canvas and in browsers with JavaScript disabled. This content can tell the users to upgrade their browser or enable JavaScript for best experience.

You can change the displayed size of the canvas using a stylesheet. The image or graphic inside the canvas is scaled during rendering to fit the styled size. This resizing can make your renderings seem distorted. In such cases, you should try specifying your width and height attributes explicitly in the <canvas> attributes, and not using CSS.

Here is an example of using this tag:

<canvas id="canvas" width="300" height="200"> Sorry, Your browser does not support <canvas> element.  </canvas>

Attributes

height

This attribute sets the height of the canvas in CSS pixels. The default value of height is 150.

moz-opaque

You can use this attribute to let the browser know whether or not canvas translucency will be a factor. If the browser knows beforehand that there’s no translucency, painting performance can be optimized.

width

This attribute sets the width of the canvas in CSS pixels. The default value of width is 300.

Examples

See the Pen HTML canvas Tag by Tutorialio (@tutorialio) on CodePen.

Further Reading

  1. Read more about the HTML <canvas> element on MDN.
  2. You can also read the HTML <canvas> tag reference on W3C.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top