HTML Elements: <canvas>

By: Dusty Arlia
Published on Saturday, September 7, 2013, 01:10 PM
Last Updated on Sunday, July 05, 2015 at 9:45 PM
Total Updates: 3

The HTML5 <canvas> element is used to create graphics in real-time using a scripting language like JavaScript (the default scripting language for web browsers). The <canvas> element only acts as a container for the graphics. The script you write does all the work in making the graphic.

Here is the basic syntax for the <canvas> element:

<canvas id="example_canvas" width="400" height="400" style="border:2px solid black">

Above you will see that the width and height attributes are each set to 400. This is the width and height of the canvas in pixels. The id example_canvas is referenced in your JavaScript with the getElementById() method. Here is an example script:

var c = document.getElementById("example_canvas");
var our_context = c.getContext("2d");
our_context.fillStyle = "#d56";

The canvas object has several methods for drawing paths, boxes, circles, characters, and adding images. You can access these methods using the id assigned to your <canvas> element. By default, the canvas element does not have a border. And you are able to add as many <canvas> elements to your HTML document as you would like.