Drawing Basic Shapes with HTML5 Canvas
HTML5 canvas is a relatively new element that can be used to programmatically draw graphics or fonts on a web page using a scripting language like JavaScript.
Canvas could enable many new site features and interactions, and potentially improve site-loading performance. In this post, I am going to describe how to draw, fill, and stroke basic shapes with the canvas element. I will also provide a list of HTML5 canvas resources for your further exploration.
It is worth nothing that all modern web browsers, including Internet Explorer 9, support canvas. Older versions of Internet Explorer back to IE7 can be made to support canvas with the inclusion of a JavaScript library like ExplorerCanvas.
The Canvas Tag
Placing the canvas tag in an HTML document is no different than placing an anchor or image, with one possible exception. You should include width and height declarations in your HTML markup. Personally, I hate to add dimensions to HTML. Dimensions, I believe, are best set with cascading style sheets, but if we try to do that with canvas, meaning that we only set the canvas size in our CSS, the element will behave unexpectedly in some browsers.
Here is the basic canvas syntax. You’ll notice — as an aside — that I am not using quotation marks around the values for the id, width, and height. HTML5 does not require them, although you may use them if you wish.
- <canvas id=example1 width=550px height=550px></canvas>
<canvas id=example1 width=550px height=550px></canvas>
HTML5 canvas elements are transparent by default. While the tag above would place a 550 pixel by 550 pixel square canvas on the page, you would see nothing. To help with the illustrations on this page, I used a CSS style declaration to place a border around the canvas. I also added a margin to position it more centrally in the page.
- #example1 {border: #000 solid 7px; margin: 20px auto;}
#example1 {border: #000 solid 7px; margin: 20px auto;}The canvas element is transparent by default; a CSS border is used to show its position in the example.
Establishing the Canvas Context
With canvas, we are going to talk a lot about the drawing context, which can be thought of as the drawing surface. To get this surface, I am going to begin by creating two variables in JavaScript. The first of these gets the canvas element from the HTML page. The second establishes a variable to represent the context.
- var canvas = document.getElementById('example1'),
- context;
var canvas = document.getElementById('example1'),
context;In the examples shown in this article, I placed the JavaScript at the bottom of the HTML page to make sure that the canvas element had been loaded to the document object model (DOM) before my script tried to grab it. If you’re using a JavaScript library like jQuery, you may wish to use a DOM loaded function. Here is what that might look like in jQuery.
- $(function(){
- var canvas = document.getElementById('example1'),
- context;
- })
$(function(){
var canvas = document.getElementById('example1'),
context;
})Next, I need to ensure that the browser being used supports HTML5 canvas. One of the best ways to do this is to learn if the canvas context exists using an if/else statement in my JavaScript.
- if(canvas.getContext){
- // draw to the canvas script goes here
- } else {
- // canvas not available message script goes here
- }
if(canvas.getContext){
// draw to the canvas script goes here
} else {
// canvas not available message script goes here
}If my test returns true, I set the context variable.
- if(canvas.getContext){
- context = canvas.getContext('2d');
- } else {
- // canvas not available message script goes here
- }
if(canvas.getContext){
context = canvas.getContext('2d');
} else {
// canvas not available message script goes here
}Notice that I have chosen the “2d” context API. At the moment, it is the only one available.
###Drawing Rectangles
One of the most basic canvas shapes is a rectangle. To draw one, I am going to use just two lines of JavaScript.
First, I am going to set the context’s _fillStyle_ attribute. This attribute represents a shape’s color or style. This code, of course, would be placed inside of the _if_ statement that I created above. You should also note that I am using an RGB color value, but I could have used any standard CSS color value.
- context.fillStyle = "rgb(200,0,0)";
context.fillStyle = "rgb(200,0,0)";
Next, I am going to use the fillRect method, which is part of the 2d context API, to paint a given rectangle onto the canvas. This method must be applied to a shape with a height and width value that is not zero. It also requires that I have previously set the fillStyle attribute.
As you will see below, the method takes four parameters: the x or horizontal coordinate of the shape’s top left corner; the y or vertical coordinate of the shape’s top left corner; the shape’s height in pixels; and the shape’s width in pixels. In the example, the shape is 75 pixels from the left, 75 pixels from the top, and 250 pixels square.
- context.fillRect (75, 75, 250, 250);
context.fillRect (75, 75, 250, 250);
If I place what we have so far inside of a function, it looks like this.
- <script>
- function example1(){
- var canvas = document.getElementById('example1'),
- context;
- if(canvas.getContext){
- context = canvas.getContext('2d');
- context.fillStyle = "rgb(200,0,0)";
- context.fillRect (75, 75, 250, 250);
- } else {
- document.write('Your Browser does not support HTML5 Canvas.');
- }
- }
- example1();
- </script>
<script>
function example1(){
var canvas = document.getElementById('example1'),
context;
if(canvas.getContext){
context = canvas.getContext('2d');
context.fillStyle = "rgb(200,0,0)";
context.fillRect (75, 75, 250, 250);
} else {
document.write('Your Browser does not support HTML5 Canvas.');
}
}
example1();
</script>Using some simple JavaScript, it is easy to draw rectangles on an HTML5 canvas.
Rectangles with Strokes
It is also possible to draw rectangles that have a stroke or border, but that do not have a fill. To achieve this, I would first apply the strokeStyle attribute that like the fillStyle sets the color or style of the shape.
- context.strokeStyle = "rgb(0,0,0)";
context.strokeStyle = "rgb(0,0,0)";
I would then call the strokeRect method, which takes the same four parameters as the fillRect method described above.
- context.strokeRect (75, 75, 250, 250);
context.strokeRect (75, 75, 250, 250);
In the context of a JavaScript function, I could create the shape with code like this.
- function example2(){
- var canvas = document.getElementById('example1'),
- context;
- if(canvas.getContext){
- context = canvas.getContext('2d');
- context.strokeStyle = "rgb(0,0,0)";
- context.strokeRect (75, 75, 250, 250);
- } else {
- document.write('Your Browser does not support HTML5 Canvas.');
- }
- }
- Example2();
- </script>
function example2(){
var canvas = document.getElementById('example1'),
context;
if(canvas.getContext){
context = canvas.getContext('2d');
context.strokeStyle = "rgb(0,0,0)";
context.strokeRect (75, 75, 250, 250);
} else {
document.write('Your Browser does not support HTML5 Canvas.');
}
}
Example2();
</script>HTML5 canvas can also draw stroked shapes.
It is, of course, possible to apply both a fill and a stroke to a single shape.
Overlapping Shapes on the Canvas
With HTML5 canvas, we can overlap shapes, so that newer shapes appear on top of older shapes. To demonstrate, I am going to draw a red square just like the one mentioned above. Then I am going to draw a green square overlapping. Here is what the code would look like.
- <script>
- function example3(){
- var canvas = document.getElementById('example1'),
- context;
- if(canvas.getContext){
- context = canvas.getContext('2d');
- //red square
- context.fillStyle = "rgb(200,0,0)";
- context.fillRect (75, 75, 250, 250);
- //green square
- context.fillStyle = "rgb(0,200,0)";
- context.fillRect (200, 200, 250, 250);
- } else {
- document.write('Your Browser does not support HTML5 Canvas.');
- }
- }
- example3();
- </script>
<script>
function example3(){
var canvas = document.getElementById('example1'),
context;
if(canvas.getContext){
context = canvas.getContext('2d');
//red square
context.fillStyle = "rgb(200,0,0)";
context.fillRect (75, 75, 250, 250);
//green square
context.fillStyle = "rgb(0,200,0)";
context.fillRect (200, 200, 250, 250);
} else {
document.write('Your Browser does not support HTML5 Canvas.');
}
}
example3();
</script>Newer shapes appear on top when canvas elements overlap.
It is worth mentioning that nothing has really happened to the red square other than it is behind the green one. I can demonstrate this, if I set the green square’s alpha channel to about 50 percent in the fillStyle attribute.
- context.fillStyle = "rgba(0,200,0, 0.5)";
context.fillStyle = "rgba(0,200,0, 0.5)";
Because canvas' fillStyle attribute can take any CSS color designation, it is possible to pass alpha channel setting.
Clear Rectangles
In canvas you can also draw clear rectangles that “cut out” shapes. To do this, you would use the clearRect method. If, as an example, I related the green square with a “clear” square, it would cut a piece out of the red square.
- context.clearRect (200, 200, 250, 250);
context.clearRect (200, 200, 250, 250);
Clear rectangles in canvas clear out fills and strokes.
Clearing the Canvas
The easiest way to clear off a canvas is to reset its size, even if you don’t change the dimensions.
- canvas.width = canvas.width;
canvas.width = canvas.width;
Canvas Coordinates
Next, we should start to take notice of the canvas’ coordinate system, which places 0,0 at the top left of the canvas. This means that an x position of 100 pixels is 100 pixels in from the left side of the canvas. A y position is 100 pixels down from the top of the canvas.
If I had a 21 by 21 pixel canvas, the middle would be at 11, 11. This becomes important when we start to position shapes on the canvas, or draw things like circles (arcs).
Drawing Arcs and Circles
In canvas, we can draw circles and arcs too. We begin drawing shapes other than rectangles using the beginPath().
- context.beginPath();
context.beginPath();
I define the shape’s fillStyle attribute below.
- context.fillStyle = "rgb(200,0,0)";
context.fillStyle = "rgb(200,0,0)";
Next, I am going to specify an arc using the arc method. This method takes six parameters that can be sort of confusing.
First, it takes an x coordinate for the center of the shape, not the edge. Second, it takes a y coordinate for the center of the shape. The third parameter is the radius of the shape. The fourth parameter describes the beginning angle in radians. The fifth parameter describes the ending angle in radians, and the sixth and final parameter describes the direction the arc will be drawn. Here are those parameters again as a list.
- x coordinate of the shape’s center point
- y coordinate of the shape’s center point
- radius
- beginning angle in radians
- ending angle in radians
- drawing direction (called anticlockwise parameter)
Here is some example code that will produce a circle.
- context.arc(275, 275, 200, 0, Math.PI*2, true);
context.arc(275, 275, 200, 0, Math.PI*2, true);
Notice that the circle’s center point will be at 275, 275 or approximately the middle of the canvas I have been using in this tutorial.
The radius, which is the third parameter, is set to 200 pixels. This means that the complete circle will be 400 pixels in diameter.
The beginning angle is at zero radians along the circle’s circumference. The ending angle is set to π times 2 or 2π.
Recall a radian is a ratio between the radius and the arc’s length. Interestingly, when you are measuring in radians, there is one spot on the circumference of the circle that has two values. That spot is at zero or 2π. I think of it as a spot on the right side of the circle. You get to this spot by following the x axis out to the right the length of the radius. By setting the beginning and ending angles at the same point on the circumference, we get a complete circle.
Wikipedia provides a helpful illustration of how radians relate to degrees on a circle.
Finally, the so-called anticlockwise parameter determines which way the shape will be drawn. Setting it to “true” means the arc will move in a counterclockwise fashion.
To actually draw the arc to the canvas I use the fill method.
- context.fill();
context.fill();
Here is the code in context.
- function example4(){
- var canvas = document.getElementById('example1'),
- context;
- if(canvas.getContext){
- context = canvas.getContext('2d');
- //red circle
- context.beginPath();
- context.fillStyle = "rgb(200,0,0)";
- context.arc(275, 275, 200, 0, Math.PI*2, true);
- context.fill();
- } else {
- document.write('Your Browser does not support HTML5 Canvas.');
- }
- }
function example4(){
var canvas = document.getElementById('example1'),
context;
if(canvas.getContext){
context = canvas.getContext('2d');
//red circle
context.beginPath();
context.fillStyle = "rgb(200,0,0)";
context.arc(275, 275, 200, 0, Math.PI*2, true);
context.fill();
} else {
document.write('Your Browser does not support HTML5 Canvas.');
}
}In canvas, a circle is drawn using an arc that has the same beginning and ending angle.
To help explain the anticlockwide parameter, I am going to reset the ending angle of my circle to π rather than 2π, drawing a half circle. Because I am drawing in the counterclockwise direction, I will be keeping the top half of the circle.
- context.arc(275, 275, 200, 0, Math.PI, true);
context.arc(275, 275, 200, 0, Math.PI, true);
Drawing a half circle in the counterclockwise direction places the shape at the top of what was the circle.
If I draw the arc in the clockwise direction, by setting the anticlockwise parameter to “false”, the half circle is flat on top or on the bottom half of the original circle.
- context.arc(275, 275, 200, 0, Math.PI, false);
context.arc(275, 275, 200, 0, Math.PI, false);
Reversing the anticlockwise parameter draws the half circle opposite of its previous position.
Summing Up
In this post, I have demonstrated how to draw basic rectangles and arcs, but I have only scratched the surface of what canvas can do. Below, you will find several resources for learning more about canvas, and you may look for future tutorials here on Ecommerce Developer.
Resources
- WHATWG Canvas Documentation
- Mark Pilgrim’s Dive into HTML5 Section on Canvas
- Mozilla Developer’s Network Canvas Tutorial
- W3School’s HTML5 Canvas Section
- Dev.Opera’s HTML5 Canvas — The Basics
- Six Revisions HTML5 Canvas Element Guide











