1. html
  2. /tags
  3. /canvas

<canvas>

Definition

The HTML <canvas> element is a container for graphics on a web page. It allows developers to create and manipulate graphics on the fly using JavaScript.

Examples

To use a <canvas> element, you must first define it in your HTML code with a width and height attribute:

<canvas id="myCanvas" width="300" height="150"></canvas>

Once you have defined a canvas element, you can use JavaScript to access it and draw graphics on it. To do this, you can use the getContext() method, which returns an object that provides methods and properties for drawing on the canvas. For example:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

With the ctx object, you can then use methods like fillRect() and strokeRect() to draw rectangles on the canvas, and moveTo() and lineTo() to draw lines. You can also use the fillStyle and strokeStyle properties to set the fill and stroke colors for these shapes.

In addition to basic shapes, the <canvas> element also allows for complex graphics, such as images, text, and gradients. You can use the drawImage() method to draw an image on the canvas, and the fillText() and strokeText() methods to draw text.

Attributes

AttributeDescriptionDeprecated
widthSpecifies the width in CSS and defaults to 300No
heightSpecifies the height in CSS and defaults to 150No

Best Practices

The HTML canvas element is most commonly used for rendering dynamic graphics on a web page, such as graphs, games, and other visualizations. This is because the canvas element provides a low-level API for drawing graphics using JavaScript, which allows for a high degree of control and flexibility.

For example, a developer could use the canvas element to create an interactive chart that updates in real time, or a simple game with complex animations and graphics.

However, it is important to note that the canvas element is not well-suited for displaying static images or text, as these can be better handled using other HTML elements.

Accessibility Considerations

While the canvas element itself may be accessible to screen readers and other assistive technologies, the content that is drawn on the canvas might not be.

To make the content on a canvas element accessible, developers can use the aria-describedby attribute to provide a description of the content, or provide alternative content within the canvas element itself that can be read by assistive technologies.

Additionally, it is important to ensure that any user interactions with the canvas are properly conveyed to assistive technologies, so that users with disabilities can fully interact with the content.

Browser Compatibility

ChromeFirefoxSafariInternet ExplorerMicrosoft EdgeOpera
YesYesYesYesYesYes