The World Wide Web Consortium (WWC) introduced Canvas with HTML5 last year. We think it’s a pretty interesting drawing tool. So, we decided to experiment with it and share our findings in the form of a short tutorial in this blog post. We’ll cover the basics and mention a couple of recommendations for deeper learning.

To start understanding Canvas, think of it as an area on your page where you can draw and render graphs. It’s user together with Javascript, taking advantage of its properties and methods. Its purpose is to be a container for graphics, as it has no drawing abilities on its own. It may seem like a simple element, however, it can be used for complex tasks, like creating 2D animations. You can see examples of what Canvas can do here. Most modern browsers support Canvas, such as Chrome, Firefox, Safari, Opera, and Internet Explorer 8 and later.

Getting Started

In order to start drawing we need to add the Canvas element to our page, we’ll do it with this code:

<Canvas id="Canvas" width="800" height="480"> Your browser does not support HTML5 Canvas</Canvas>

As you may notice, we defined a width and height for this element. If you don’t define the size, it will use the default values, which are 300x150px. Inside the Canvas tag, you can write a message to be displayed if the browser does not support it.

1

The Canvas element is displayed in light blue.

Once we have added our Canvas element, we’ll use Javascript to get the “context”. You can insert Javascript code in the HTML header, a script block or even in another file. The code should look like the following:

var d_Canvas = document.getElementById('Canvas');
var context = d_Canvas.getContext('2d');

And now we are ready to draw!!!

We’ll start with the basic forms and shapes:

Text

In order to show text in our element, we need to take care of three things: font, fillStyle, and fillText. More specifically, this is what you should do:

– Define size and font type in the “context.font” property.
– Define text color in the “fillStyle” property.
– Use the “fillText” function as in the example below. The first parameter is for the text to show, and the next two are the X and Y axes, respectively.

context.font = "30px Arial";
context.fillStyle="#000";
context.fillText("Hello, World! This is a text", 20, 100);

2

Canvas now displays a gray color.

Square

To draw a square or a rectangle we use “fillRect”. Once again, we are defining the color of our square with the “fillStyle” function. When using “fillRect”, we have to include the following parameters: (positionX, positionY, width, height).

Example:

context.fillStyle = 'red';
context.fillRect (175, 75, 50, 50);

3

And this is what we get from Canvas.

Circle

To draw a circle we use “beginPath” first and then “arc”. First draw the outline and then call the “fill” function. The code should look like this:

context.beginPath();
context.fillStyle = 'green';
context.arc(200, 100, 50, 0, Math.PI * 2);
context.fill();

5

And this is the result.

The “arc()” function takes the following parameters: (x, y, radius, starting angle, ending angle, anticlockwise). As you may notice, in this example we didn’t use the anticlockwise parameter, as it is optional, and it wouldn’t have changed the result.

If you’re wondering about the meaning of those parameters: here’s what they mean]:

Starting angle: angle in radians to start drawing the outline (0 will be at the three o’clock position)

Ending angle: the ending angle in radians.

CounterClockWise: boolean value that draws anticlockwise when true, and clockwise when false.

Gradients

We can fill a shape with a color gradient, which means that a filling can start using one color and end with another. To do this in Canvas, we create a gradient using the “createRadialGradient” method, in which we specify two circles. The first circle is where the color is going to begin changing, and the second one tells Canvas where the color gradient is going to end. To declare every circle, we pass the X and Y coordinates of the circle’s center and radius to the “arc” function. Take note, the gradient could use other fillings if needed.

var grd = context.createRadialGradient(190, 60, 15, 190, 80, 50); //x1, y1, radius1, x2, y2, radius2.

Once we have declared the reach of the gradient, the next step is to set the gradient’s colors. We do this by using the “addColorStop” method, which requires two parameters. The first one is the “stop” or the point in which the color will begin. Stops go from 0 to 1, so make sure you distribute your colors between those numbers. The second parameter is the color we want to paint on that stop.

grd.addColorStop(0, '#F00');
grd.addColorStop(.2, '#FF0');
grd.addColorStop(.4, '#0F0');
grd.addColorStop(.6, '#0FF');
grd.addColorStop(1, '#00F');

To assign our new gradient to our shape we use the “fillStyle” method to tell the context that its filling is going to be the gradient we just built. Finally, we invoke the “fill” method to tell the context to fill the shape with the gradient.

Example:

context.beginPath();
context.arc(200, 100, 35, 0, Math.PI * 2); // A regular circle figure.
context.fillStyle = grd
context.fill();

6

And you’ll get this result.

Ellipse

For ellipses, use the “ellipse()” function, which requires the following parameters: (x, y, radiusX, radiusY, rotation, start angle, ending angle, anticlockwise). The rotation parameter indicates how much will the ellipse turn on the axis. In radians, as usual.

Here’s an example:

context.beginPath();
context.ellipse(200, 100, 50, 20, 0, 0, Math.PI*2);
context.stroke();

7

And this is how it would look.

Line

We use the “beginPath” function to declare that we are about to draw a new line path. Next, we use the “moveTo” function to state the starting position (imagine that you are moving a cursor). And then we use “lineTo” to draw a straight line from the starting position to the ending position. And finally, we need to call stroke() to “paint” through the covered path.

Example:

context.beginPath();
context.moveTo(75, 50);
context.lineTo(350, 180);
context.stroke();

8

The result.

A pretty cool thing we can do with Canvas is to render an image. We can draw an image directly from an existing image element within the HTML document or use an external picture.

In order to use an internal image element, we have to include the image element with a specific ID inside the document.

<code><img id=”dog” src=”http://3.bp.blogspot.com/-lCei4CIR7J8/UOXuPWztz5I/AAAAAAAAAAw/iNkkVQzUV88/s1600/cute_little_dog_wallpaper-1024×1024.jpg” alt=”Dog” width=”100″ height=”110″></code>

Then, we get the image element by its ID using Javascript, and use the “drawImage” method to render the image in the canvas:

var img = document.getElementById("dog");
context.drawImage(img, 110, 0, 180, 200);

In this case, the “drawImage” method has the image element as its first parameter, then the X and Y coordinates, and finally the width and height of the image in the canvas. Also, you can see that the original HTML element is visible, so it is recommended to hide it.

9

This is the result.

But, if we want to use a picture that is outside of our HTML document, then we have to create an object of the “Image” type first. Then we can assign it an external source path. We invoke the drawing method on the “onload” event of the image so the picture can draw itself the moment it’s fully loaded. If we don’t do this, the drawing method may fail because the picture won’t load when the drawing method is invoked.

var image = new Image();
image.src = "http://www.mycatspace.com/wp-content/uploads/2013/08/adopting-a-cat.jpg";
image.onload = function(){
context.drawImage(image, 100, 0, 200, 200);
};

10

This is what you get with the code above.

With Canvas, there are no limits to your creativity, just let it flow…

If you want to avoid repetitive tasks, there are some frameworks that can help you speed up your work. Some of them specialize in picture handling and others in making charts or creating filters and effects. Take a look at FabricJS, ChartJS and PaperJS if you want to explore these possibilities.

Another great feature of Canvas is that you can create graphic content in real time, and even respond to user events. A couple of final tips: remember that in order to start/reset a path you need to call the “BeginPath()” function. Here’s a pretty useful cheat sheet with frequently-needed code, and a live example you can use for experimentation purposes.

We hope you found this post useful! Let us know what you think in the comments section.

Thanks for reading!

J.