report

HTML5 Draw Tutorial: Basics of Canvas Drawing

A step-by-step tutorial for HTML5 canvas drawing

In this tutorial I'm going to demonstrate how to use the canvas element in HTML5 to create wonderful graphics for your website. The HTML5 web standard adds quite a few new features to HTML, the language of all webpages, and one of them is the canvas element. The canvas allows you to draw using JavaScript code so you can be very creative with what's being displayed. I'll discuss two examples of HTML5 canvas drawing that use some of the basic drawing features.

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

The first step is to create a basic .html file with some HTML5 code in it. This is our empty HTML5 page. In the next steps of this tutorial we'll add the canvas and the JavaScript code to draw something.

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:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>HTML5 Tutorial: Basics of Canvas Drawing</title>
</head>
<body>
</body>
</html>

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.

Each HTML webpage consists of a html element and in it there is a head elemtent and a body element. In the head you can find all kinds of information that is not part of the page itself but that's still needed, such as the title or links to other files (like CSS and JavaScript files). For now we only use the title element. As you can see the body element is empty and that is why there is nothing on the webpage! We are now going to add the canvas element which allows us to draw on that part of the webpage.

Adding the HTML5 canvas element

You can add a canvas element by adding the following to the body element of the above HTML5 webpage:

<canvas id="mycanvas" width="300" height="300"></canvas>

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.

The id is required as an identifier so we can refer to the canvas in our JavaScript code. This id must be unique on your webpage - you cannot have another element with the same id.

Your HTML5 webpage should now look like this:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>HTML5 Tutorial: Basics of Canvas Drawing</title>
</head>
<body>
<canvas id="mycanvas" width="300" height="300"></canvas>
</body>
</html>

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!

Using JavaScript to draw on the HTML5 canvas

To draw on the HTML5 canvas you need to write some JavaScript code that says what needs to be drawn. JavaScript is a well-known scripting language for the web and it has been used for many things such as interactive websites and web applications.

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:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>HTML5 Tutorial: Basics of Canvas Drawing</title>
</head>
<body>
<canvas id="mycanvas" width="300" height="300">
</canvas>
<script type="text/javascript">
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
</script>
</body>
</html>

We have added some JavaScript with two lines of code. The first line creates a variable called canvas which contains the canvas element. If you have used a different id then you should also change this line. The function getElementById gives you the element in the HTML document with that id so it's important that you search for the element with the id of the canvas. The second line gives us a variable ctx with the drawing context of the canvas element. In this case it's the 2D drawing context because we're going to do two-dimensional drawings.

Example 1: Drawing some rectangles on the HTML5 canvas

Let's start with something simple: just some rectangles! Add the following code to the JavaScript code of your webpage:

ctx.strokeStyle = "rgb(0, 0, 255)";
ctx.strokeRect(10, 10, 50, 50);
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillRect(30, 30, 50, 50);

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:

ctx.fillStyle = "rgb(255, 0, 0)";
ctx.fillRect(10, 10, 50, 50);

ctx.fillStyle = "rgb(0, 255, 0)";
ctx.fillRect(35, 35, 50, 50);

ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fillRect(100, 10, 100, 100);

ctx.fillStyle = "rgb(255, 255, 0)";
ctx.fillRect(120, 30, 20, 20);

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:

ctx.beginPath();
ctx.arc(150, 150, 100, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fillStyle = "rgb(255, 0, 0)";
ctx.stroke();
ctx.fill();

ctx.beginPath();
ctx.arc(120, 130, 20, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.stroke();
ctx.fill();

ctx.beginPath();
ctx.arc(123, 133, 4, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.stroke();
ctx.fill();

ctx.beginPath();
ctx.arc(180, 130, 20, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.stroke();
ctx.fill();

ctx.beginPath();
ctx.arc(183, 133, 4, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.stroke();
ctx.fill();

ctx.beginPath();
ctx.arc(155, 165, 60, 0, 3, false);
ctx.closePath();
ctx.lineWidth = 5;
ctx.strokeStyle = "rgb(255, 255, 0)";
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.stroke();
ctx.fill();

Do I need closePath() ?

It's a little more complex: you don't always need closePath() when you're filling or stroking as these commands also close the path. You can do the following to get a circle as well:

ctx.beginPath();
ctx.arc( ... );
ctx.fillStyle = ...
ctx.fill();

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 by this Author


Comments 11 comments

Butch News 5 years ago

I learned something new. Thanks. Regards from Butch


simeonvisser profile image

simeonvisser 5 years ago Author

@Butch News: Nice to hear that! It's a new web standard after all so it is new for many people.


DonDWest profile image

DonDWest 5 years ago from Halifax, Nova Scotia, Canada

Hmm, I better brush up on my Javascript. Good tutorial.


simeonvisser profile image

simeonvisser 5 years ago Author

@DonDWest: JavaScript is being used more and more to create dynamic and interactive websites. And now you can even draw your webpages with JavaScript alone. So yes, you'll need to have some mastery of JavaScript if you want to create a modern website.


agvulpes profile image

agvulpes 5 years ago from Australia

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 profile image

simeonvisser 5 years ago Author

@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 :)


lex123 profile image

lex123 5 years ago

Awesome tutorial! I'll come back to this hub and read it again. Thanks for sharing your knowledge.


simeonvisser profile image

simeonvisser 5 years ago Author

@lex123: Thanks! :)


John Allsopp 5 years ago

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

http://westciv.com/tools/canvasConsole/


philipandrews188 profile image

philipandrews188 5 years ago

Great tutorial on HTML5!


Meghna 4 years ago

How do you give a glow effect to a line in an animated manner through HTML5 ?

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article