HTML5 Canvas – Draw Shapes

In the last article on HTML5 Canvas, we have discussed about the basics and created a simple rectangular shape. In this tutorial, we will create more shapes – rectangles and squares with various styles, lines, triangles and combined shapes.

You will recall that creating a rectangle in canvas is pretty simple. We need to provide the origin point of rectangle with X and Y coordinate with respect to the canvas origin and then define the width and height. We can write the arguments of the fillRect method like this:

ctx.fillRect(Xstart,Ystart,Width,Height);

With fillRect method, we have already drawn a pretty looking filled rectangle. There are two more functions for drawing rectangles on the canvas. These are:

strokeRect(Xstart,Ystart,Width,Height) – To draw a rectangular outline (No fill)

clearRect(Xstart,Ystart,Width,Height) : To clear the specified rectangle making it fully transparent

Let’s create a checker board like this. It will help us to learn how to draw rectangles of various types.

As you can see, there are eight black squares at equal intervals inside a big square. And all these squares are surrounded by one more square which acts like the border for this image. Drawing a square, as you know, is simple. For squares, we need to keep the width and height of the rectangle same.

Here is the complete HTML code for drawing this shape:

<html>
<head>
<script type="application/javascript">
function drawRectangle() {
var canvas = document.getElementById('canvas-tutorial');
    if (canvas.getContext){
        var ctx = canvas.getContext('2d'); 
        ctx.strokeRect(40,40,400,400);
        ctx.fillRect(40,40,100,100);
        ctx.fillRect(240,40,100,100);
        ctx.fillRect(140,140,100,100);
        ctx.fillRect(340,140,100,100);
        ctx.fillRect(40,240,100,100);
        ctx.fillRect(240,240,100,100);
        ctx.fillRect(140,340,100,100);
        ctx.fillRect(340,340,100,100); 
        ctx.strokeRect(30,30,420,420);
}
    }
</script>
<style>
    #canvas-tutorial
    {
     border: 2px solid #FF0000; 
    }
</style>
</head>
<body onload="drawRectangle();">
<canvas id="canvas-tutorial" width="480" height="480">
"Sorry, your browser does not support canvas!"
</canvas>
</body>
</html>

Here, the first square is drawn with strokeRect method, where we are drawing an outline starting from (40, 40) with width and height equal to 400 each. Inside this square, we will put eight black squares. Note here, that we are not defining the fill color here. By default, the fill and stroke color is black.

After this outline, eight square blocks are drawn with fillRect method a width and height equal to 100 pixels. Just note their x and y coordinates to see how we are placing these squares. Finally, one more square outline is drawn with a width and height equal to 420 pixels which acts as the border. Pretty simple! Use this code and try it in a web browser.

Can you think some other method to create the same shapes? We will tweak our code a little to use clearRect method.

        ctx.fillRect(40,40,400,400);
        ctx.clearRect(140,40,100,100);
        ctx.clearRect(340,40,100,100);
        ctx.clearRect(40,140,100,100);
        ctx.clearRect(240,140,100,100);
        ctx.clearRect(140,240,100,100);
        ctx.clearRect(340,240,100,100);
        ctx.clearRect(40,340,100,100);
        ctx.clearRect(240,340,100,100); 
        ctx.strokeRect(30,30,420,420);
        ctx.strokeRect(40,40,400,400);

Here, we are first creating a black square of 400 pixels width and height. After that, we are clearing the squares shapes from eight places. At the end, we are adding one extra square outline. Great… You can draw rectangles and squares pretty easily now! And since rectangles are the only primitive shape in canvas, it’s good to learn about this in details to build the right foundation.

Moving ahead, coming up next – lines, triangles, circles and arcs!

Canvas Paths

As I have mentioned earlier, rectangles are the only primitive shape in canvas. For drawing all other shapes, we need to use canvas paths. And for using paths, we have to include a few extra lines of codes.

  • beginPath()
  • closePath()
  • stroke()
  • fill()

To start creating any new shape with path, we call beginPath() method. So, if you want to create multiple shapes inside the canvas, you need to call this method every time. The next thing we need to do is to call moveTo() method. This sets the starting point of the path we are going to create. Suppose you are going to draw a shape on a page, first thing you do is to move your pen or pencil to the starting position. Here, we are doing exactly the same. The moveTo method takes two arguments as x and y coordinates of the starting point.

After beginPath() and moveTo() methods, we draw the actual paths in form of lines, arcs or curves. This I will explain shortly.

Once we finish drawing the paths (lines or arcs); we call closePath() method. And finally, we use stroke() and fill() methods to define whether we want just the outline or fill the drawn paths. Enough theory here, let’s create some paths now!

Drawing a Line

Line is a type of path and for drawing a straight line, we use lineTo() method.

lineTo(x, y)

This method takes two arguments x and y which are the end point of the line. As already discuss, we know to define the starting point, we use moveTo() method. So, in this example, we will create a simple straight line.

        ctx.beginPath();
        ctx.moveTo(50, 50);
        ctx.lineTo(200, 200);
        ctx.closePath();
        ctx.stroke();

Do you find anything new here? It’s pretty the same codes we discussed earlier. We are starting our line at coordinates (50, 50) and drawing till (200, 200). Replace the codes we used to create rectangles with these and you get a line like this.

Draw a Triangle

Once you learn how to create a straight line on canvas, it’s not a big deal to create other shapes like triangle, squares, rectangles, or anything which can be created with lines. Let’s create a triangle now!

        ctx.beginPath();
        ctx.moveTo(50, 50);
        ctx.lineTo(200, 200);
        ctx.lineTo(350, 50);        //Line from (200, 200) to (350, 50)
        ctx.lineTo(50, 50);        //Line from (350, 50) to (50, 50)
        ctx.closePath();
        ctx.stroke();

Here, we are just including two more lines of codes after the first line to introduce two more lines. Note here that we are not using moveTo in between. This is because the starting point of the next line is the end point of the previous line. Let’s create one more similar triangle with filled color, just below this triangle.

        ctx.beginPath();
        ctx.moveTo(50,350);
        ctx.lineTo(200,200);
        ctx.lineTo(350,350);   
        ctx.fill();

Are we missing here something? If you notice carefully, you would know that I have escaped the closePath() method here. This is because, when we call the fill() method, the open shape is closed automatically. Thus it becomes optional and we can escape the closePath(). The complete HTML code for drawing the two triangles is as follows:

<html>
<head>
<script type="application/javascript">
function drawRectangle() {
var canvas = document.getElementById('canvas-tutorial');
    if (canvas.getContext){
        var ctx = canvas.getContext('2d');
        // Stroke Triangle   
        ctx.beginPath();
        ctx.moveTo(50,50);
        ctx.lineTo(200,200);
        ctx.lineTo(350,50)
        ctx.lineTo(50,50)
        ctx.closePath();
        ctx.stroke();      
        // Filled Triangle
        ctx.beginPath();
        ctx.moveTo(50,350);
        ctx.lineTo(200,200);
        ctx.lineTo(350,350);      
        ctx.fill();
}
    }
</script>
<style>
    #canvas-tutorial
    {
     border: 2px solid #FF0000;   
    }
</style>
</head>
<body onload="drawRectangle();">
<canvas id="canvas-tutorial" width="480" height="480">
"Sorry, your browser does not support canvas!"
</canvas>
</body>
</html>

You can see how powerful the canvas path is! Why not do create a few shapes, before we move ahead? Try creating following shapes on your own. No help or codes here, it should not be a big deal! Let me know in the comments section below if you get stuck somewhere.

I am sure you are enjoying drawing these shapes. Let’s be a little more creative now. The next task is to create a full chess board with 64 squares. This is very similar to the checker board we created in the beginning. Only difference is that, here you need to create 32 black circles. Quite boring (and probably tedious) work, isn’t it?

chess-board

Let’s make it really interesting and fun. Go through the codes below:

<html>
<head>
 <script type="application/javascript">
 function drawRectangle() {
 var canvas = document.getElementById('canvas-tutorial');
   if (canvas.getContext) {
     var ctx = canvas.getContext('2d');
     var x_shift;
     for (var i = 0; i < 4; i++) {
       for (var j = 0; j < 8; j++) {
         var x_shift = j % 2 == 0 ? 60 : 0;
         ctx.fillRect(i * 120 + x_shift, j * 60, 60, 60);
       }
     }
    }
  }
 </script>
 <style type="text/css">
 #canvas-tutorial
 {
 border: 2px solid #000000;
 }
 </style>
</head>
<body onload="drawRectangle();">
 <canvas id="canvas-tutorial" width="480" height="480">
"Sorry, your browser does not support canvas!"
</canvas>
</body>
</html>

Here,I have used two ‘for’ loops in JavaScript to make 32 black squares. The possibilities are limitless, you just need to think a little to get the shape you want.

Great going till now! In next article, we will discuss the second and third parts of the canvas paths i.e. arc and curve. We will learn to create circles, arcs and curves with various styles and shapes. Stay tuned with me for the next article.

>> Circles, Arcs and Curves

2 thoughts on “HTML5 Canvas – Draw Shapes

Leave a Reply