Simeon Visser is a writer who enjoys covering topics such as technology and travel.
This tutorial is aimed at people who may know a little about how HTML works but who are not familiar with the canvas element. You may just be starting out in web development or you may just want to know more about the canvas element in HTML5. This tutorial will go through all the steps without assuming too much background knowledge. I do recommend reading a little bit about HTML so you know what an element is and what HTML markup generally looks like. If something is unclear, please leave a comment below.
Importance of Web Standards
With so many computers and web browsers accessing the internet, it's very important to comply with all the web standards that exist. If you're writing a webpage in HTML5 then you indeed want to make sure you it's valid according to the HTML5 web standard. You can use the W3C validator to make sure your webpage is indeed an HTML5 webpage. This is why we will start with a basic empty HTML5-valid webpage and then I'll add all the things needed for drawing on the canvas.
Creating a Basic HTML5 Webpage
Here's what you need to do:
- Open a text editor.
- Copy the code below and put it in a new file
- Save the file as a basic text file and give it a name that ends in .html (make sure it's something like name.html and not name.html.txt. If that's the case then you need to rename it and open it again in your text editor).
If you're using Windows you should use either NotePad or WordPad but not Microsoft Word. The reason for this is that you want to save your work as a basic text file, not with added information. If you're using GNU/Linux or Mac OS X, just use your favorite text editor that allows you to easily create and save basic text files. It's even better to use one of those programmer text editors that have additional features for programmers and web developers. But don't worry: you can always download one of those later when you're more into web development and computer programming.
Here's an empty HTML5 webpage:
Open this file in your web browser. You should see an empty page and the title of the webpage is "HTML5 Tutorial: Basics of Canvas Drawing". If you can see this then you've successfully created a HTML5 webpage.
When you're writing HTML or computer code it's important to check regularly whether you're doing it correctly. You write a few bits of code and then you check if the webpage looks the way you want it to look. If it does you can move on to the next thing and if it doesn't then you can fix it right away.
Adding the HTML5 Canvas Element
You can add a canvas element by adding the following to the body element of the above HTML5 webpage:
What does this mean? It means you are defining a canvas element with the attributes id, width and height. These are all required for this tutorial. You need to specify the width and height of the canvas in number of pixels so the web browser knows how big the canvas is. If you do not specify the dimensions of the canvas then the default width is 300 pixels and the default height is 150 pixels. In our tutorial we need a bigger canvas so we use a width of 300 and a height of 300.
Your HTML5 webpage should now look like this:
If you view the webpage in your browser now you won't see any difference compared to how the webpage looked before. It is still a white empty webpage. That's because we haven't drawn anything on the canvas yet: the canvas is there but the background color is white by default so you can't see it yet.
It's time to draw on the canvas!
Here's what we need to do: we need to find a way to refer to the canvas element and then we need to write some commands to draw on the canvas. We do this by getting a so-called drawing context of the canvas. We can use the context to run some commands that specify what needs to be drawn.
Have a look at the following and make sure your webpage also looks like this:
Example 1: Drawing Some Rectangles on the HTML5 canvas
To understand the above code we need to know the difference between stroking and filling. When you stroke you simply draw the outline of the rectangle and when you fill you also color the inside of the rectangle. To change the color in which you stroke or fill, you need to change the strokeStyle or the fillStyle. After that you can call strokeRect or fillRect to stroke or fill the rectangle at a particular location.
You can specify a color using the RGB color model (red / green / blue) or you can use hex values. I've decided to use the RGB color model because it's easier to understand although hex value work exactly the same (but we can look at that at some other time). For RGB you need to specify how much red, green and blue should be used to create the color (hence three values to specify). The values are from 0 to 255 where 0 means nothing of that color and 255 means everything of that color. You can think of a red, a green and a blue light that are turned on to some extent and together they create the color. This means the color (0, 0, 0) is black whereas (255, 255, 255) is white.
The values that strokeRect and fillRect need are the x-coordinate, the y-coordinate, the width and the height of the rectangle. These are called the arguments of strokeRect and fillRect. These are not necessarily pixels but they are in the coordinate system of the drawing context. The top-left corner is (0, 0) with the x-axis being the horizontal axis and the y-axis being the vertical axis. For example a higher x-coordinate means you've moved more to the right and a higher y-coordinate means you've moved more downwards.
In the first two lines we're stroking a rectangle in the color blue and in the last two lines we're filling a rectangle in the color red. It should look like this:
Similarly, the following code produces four filled rectangles in the colors red, green, blue and yellow. Just remove the previous code and replace it with the following:
It will look like this:
Example 2: Drawing a Smiley Face on the HTML5 Canvas
We can now move on to a little more complex drawing involving circles and arcs. We are going to draw a smiley face which is basically nothing more than some colored circles in the right positions. I'm going to give you the code first and then I'll explain in more detail what's going on. Just remove the drawing code of the previous example and replace it with the following:
Do I need closePath()?
It's a little more complex. You don't always need closePath() when you're filling or stroking because these commands also close the path. You can do the following to get a circle as well:
How Does Drawing the Smiley Face Work?
What are all those beginPath and closePath commands doing there? Let's begin by having a closer look at fillRect of the previous example. It's important to realize that this command does two things: it creates the rectangle but it also fills it in a certain color. You don't always want to do these things together; when you're creating a custom shape you might want to do all the drawing first and then stroke or fill it. That's what we're going to do here. All the drawing commands together are called a path and after that we're going to decide how to display the path (by stroking or filling it).
The first arc is used to draw the red face, the next four arc commands are used to draw the white eyes with blue pupils and the last arc is used to draw the mouth. Notice how we're stroking and filling this arc: even though we're not drawing a full circle we can still fill it with a color and thereby creating the mouth.
When you create a path with beginPath you can then do all kinds of drawing commands to create your custom shape. You can then close the path with closePath. We then specify the strokeStyle or fillStyle and then we run some stroke or fill commands to draw the shape. You can also specify the styles first and then create the path. The stroke and fill commands must always come last because they use the strokeStyle and fillStyle as well as the path that you just created.
How to Draw Arcs on the HTML5 Canvas
We're going to use the arc command to create circles or parts of circles. To draw an arc you need to specify its x-coordinate, its y-coordinate, its radius, the start angle, the end angle and whether you want to draw counter-clockwise or not. The radius indicates how big the arc or circle can be (its the mathematical radius of a circle). The start and end angles indicate where you want to start with drawing the arc and where you want to end drawing the arc. This is useful when you're not drawing a full circle but only a half circle. Finally, you need to say whether you want to draw counter-clockwise or not (true if you want and false if you don't want this).
The start and end angles of the arc are specified in radians which range from 0 to 2 times the mathematical constant pi. The value 0 for the start angle means you're starting in the east (at the 3 o'clock position of a clock) and an end angle of 2 * pi means you want to draw a full circle (you want an arc of 2 * pi in radians so that's a full circle).
For example, if you want a half circle you would have a start angle of 0 and an end angle of pi instead of 2 * pi. This half circle would be the bottom half of a circle. If you want the top half, you need to have a start angle of pi and an end angle of 2 * pi.
As an example, a circle at (100, 100) with a radius of 50, starting to draw from the east (0) and drawing a full circle (2 * pi) clockwise (false for counter-clockwise) would be ctx.arc(100, 100, 50, 0, Math.PI * 2, false); Try playing with the start and end angles to get an idea of what their values should be when you don't want to draw a full circle.
Notice that for the last arc I use a value of 3 instead of pi (3.14...) so that's slightly less than a half circle. This creates a nice touch for the mouth of the smiley face. Notice that I'm also specifying the lineWidth which obviously changes the width of the line around the mouth. This value for lineWidth is used when stroking.
How did I come up with all the values for the coordinates and the angles? I just played around for a while until I got what I wanted. When you're familiar with the coordinate-system and the angles you know what changes you need to make to move the eyes or to make the mouth bigger.
More HTML5 tutorials
- HTML5 Tutorial: Drawing Circles and Arcs
Drawing circles and arcs in HTML5 can be quite a challenge. In this tutorial I explain how to draw circles and arcs and how the angles of arcs are measured. This tutorial contains many examples.
- HTML5 Tutorial: Text Drawing with Fancy Colors and Effects
You can do much more than just drawing text in HTML5! In this tutorial I'll show various effects to make some fancy texts, including shadows, gradients and rotation.
This article is accurate and true to the best of the author’s knowledge. Content is for informational or entertainment purposes only and does not substitute for personal counsel or professional advice in business, financial, legal, or technical matters.
Meghna on February 23, 2012:
How do you give a glow effect to a line in an animated manner through HTML5 ?
philipandrews188 on July 05, 2011:
Great tutorial on HTML5!
John Allsopp on March 24, 2011:
Very nice intro to canvas.
for people who don't feel super confident with JS/DOM, I wrote the CanvasConsole which makes it simple to explore the Canvas and see the results, with little JS knowledge - it's also great for experimenting if you do
simeonvisser (author) on February 25, 2011:
@lex123: Thanks! :)
lex123 on February 25, 2011:
Awesome tutorial! I'll come back to this hub and read it again. Thanks for sharing your knowledge.
simeonvisser (author) on February 20, 2011:
@agvulpes: Thanks, I agree that it's not a short page but at least it is a thorough explanation of the basics of canvas drawing :)
Peter from Australia on February 19, 2011:
Too much to absorb in one sitting so I'm bookmarking so that I can have a play around at a leisurely pace. Nice tutorial. Thumbs up
simeonvisser (author) on January 02, 2011:
DonDWest from Halifax, Nova Scotia, Canada on January 02, 2011:
simeonvisser (author) on December 31, 2010:
@Butch News: Nice to hear that! It's a new web standard after all so it is new for many people.
Butch News on December 31, 2010:
I learned something new. Thanks. Regards from Butch