How to draw basic shapes with HTML5 Canvas

Here I’ll show you how to draw basic shapes with HTML5 Canvas.
I’m creating the canvas element in JS so no need to have it in HTML for the moment.

var canvas = document.createElement('canvas'),
    w = canvas.width = 600,
    h = canvas.height = 400,
    c = canvas.getContext('2d');

document.body.appendChild(canvas);

Now the canvas variable keeps the instance of the canvas element. w and h keep the width and height of the canvas element. We can use them later to clear the whole canvas area.
c is the context of this canvas. This context gives us the methods and objects to draw on the canvas element.

Rectangle

Let’s draw a rectagle:

    c.fillStyle="blue";
    c.fillRect(100, 100, 150, 100);

In order to draw a rectangle we need to set the color which will fill the rectangle.
We can give it a string with a color name (e.g. “red”, “blue”, “pink”), but we can also give it RGBA, HSLA and hex values.

After that we call the fillRect() method which requires 4 parameters: fillRect(x, y, width, height).
You can see an example below:

Circle

var centerX = 100,
    centerY = 100,
    radius  = 50;
c.beginPath();
c.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
c.fillStyle = 'blue';
c.fill();
c.lineWidth = 4;
c.strokeStyle = 'red';
c.stroke();
c.closePath();

We can draw a circle using arc() method and making a full arc of 360 degrees.
The arc() method requires 6 parameters as follows:

context.arc(centerX, centerY, radius, startAngle, endAngle, anticlockwise);

The arc() method needs the beginPath() to be called first because it actually gives us a path of a shape. If that’s a closed shape we can fill it with color.
So we can draw a circle filled with the color we give to fillStyle, but also we can draw a stroke on that circle using strokeStyle and stroke() method.
Here is an example of a circle drawn on canvas:

Will continue on this …

Leave a Comment.