Introduction to HTML5 Canvas with Java Script
2Friends, have a good time here on “Graphic Mania”. In this tutorial we are going to deal with the HTML5 “Canvas”. We will see how this HTML5 specific “Canvas” tag is capable of drawing graphics when used along with Java Script.
This tutorial for beginner HTML5 developers and will cover both HTML5 and Java Script. To complete this tutorial you need to have a web browser such as Firefox or Chrome and text editor to write the code. Also, you can download the final source file through the download button at the end of this tutorial.
Step1. Some words about HTML5
HTML5 is similar to HTML and DHTML, but with the introduction of new “Tags”, “Attributes” and “Events”. To make some meaningful content you have to use Java Script and maybe PHP, CSS etc. along with HTML5.
HTML5 in 2011 is still under progress and is yet to become standard across all web browsers. But you can definitely say that HTML5 in the future is going to take its own place, as “IT” and “Computer Giants” like IBM, Apple, Google, Microsoft, Mozilla and so on are active groups looking after HTML5 development.
So let me introduce our HTML5 tag i.e. “Canvas” and our HTML5 attributes, such as “id”, “width” and “height”.
For more info on HTML5, follow http://www.w3schools.com/html5/html5_intro.asp
Step2. What is HTML5 “Canvas”?
The Canvas is a rectangular area in which you can draw graphics using Java Script.
In tag form it looks like this:
<canvas></canvas>
Let us start experimenting with it. Let us put these above tags in an HTML file.
Step3. Canvas in HTML file
For this step we will make a simple HTML file to start with. So open your favorite text editor (the latest Adobe Dreamweaver will be the best option for this tutorial.) I am using Notepad though.
In your text editor type the following tags,
<canvas> </canvas>
Now save this file as “MyCanvas.html” in a folder you’ve made (if you haven’t, please make a new folder for this tutorial.)
If you try to open this “MyCanvas.html” file in a browser, you will not see anything, but the fact is that your canvas with default width and height is absolutely ready and is right there inside your webpage. To reveal this secret, we will add a border to our fresh new canvas we have just created.
What we will need to add a border to our canvas? There are several ways of adding a border to an HTML5 canvas element,
1) Using CSS file. (We are not using this method for this tutorial)
2) Using Java Script. (We are going to see Java Script in the following steps)
3) Using style attribute for the canvas tag. (For this tutorial this is the right way)
So we will use the third option i.e. the “style” attribute as,
style = “border:1px solid”
So let’s modify our ““MyCanvas.html” by adding the “style” attribute as shown below,
<canvas style = “border:1px solid”> </canvas>
Now save and open this file to see the black border around your canvas. I have tested this in “Mozilla Firefox 6.0.2” and “Google Chrome 14.0.835.187”. It works absolutely fine.
Please note that, to keep it easily understandable, I intentionally kept our HTML in a non-standard form. In the following steps we will make it a standard HTML file with body, title, etc. tags. But for now, let us keep it simple.
Step4. Adjusting Canvas width and height
Continuing with the above step we will adjust the width and height of the canvas with our choice. Again we have to use attributes “width” and “height”. So let’s modify the “MyCanvas.html” file as shown below,
<canvas width = “500” height = “300” style = “border:1px solid” > </canvas>
Save and open this file to see the updated width and height of our canvas.
Step5. HTML5 + Java Script
A blank canvas is of no use. You will only like it if it has a paint art drawn on the canvas. Do you remember the “Mona Lisa” painting? So you need to have something and do something on the canvas.
But HTML5 is a tag-based language, meaning that its job is to provide a context but it does not execute any advanced interactions. So JavaScript comes handy to process those advanced interactions. But wait… How will we bridge these two languages? After all, they are different technologies. I mean our canvas is defined in HTML and we need to draw some graphics inside it using another language, JavaScript.
The solution is absolutely simple. We will need one more HTML attribute i.e. “id”. This attribute assigns a unique id to HTML elements (i.e. the canvas in our case). What to do with this “id”? We will use this “id” to access our canvas element and its properties from Java Script. Luckily, today’s browsers are smart enough to handle these two technologies.
So let us modify “MyCanvas.html” to add a new attribute “id” as shown below,
<canvas id = “MyCanvas” width = “500” height = “300” style = “border:1px solid” > </canvas>
This id (i.e. “MyCanvas” in our case) is utilized in Java Script. It references our canvas defined in html. This way we will have direct access to the canvas element and its properties. Further using JavaScript, we can manipulate this canvas element very smoothly.
Save your file with this new addition.
Step6. Some words about Java Script
Java Script is not a Java. It was first introduced by Netscape (code name “Spider Monkey”). Java Script is a dynamic lightweight programming language which is used for adding interactivity to web pages. This is not a dedicated software development programming language, rather it is used for building rich internet applications. The best example of Java Script is “Google Maps”.
This scripting language is supported by almost all standard browsers. So you need not worry much about your Java Script compatibility issues. Java Script can read and write HTML elements and HTML5 elements. This feature will allow us to find our “id’ attribute we have added in the previous step. For more info on Java Script, follow
http://www.w3schools.com/js/js_intro.asp
Step7. Preparing Java Script
So let us prepare our Java Script file. Using your text editor create brand new file and add the following lines,
var myImage = new Image();
myImage.src = “GraphicManiaLogo.png”; //url of a targeted file
var canvas = null;
var context2D = null;
Save this file as “DrawImage.js” in the same folder for this tutorial. Also, put an image file (mine is “GraphicManiaLogo.png”) placed in the same folder for this tutorial.
Ok, now we will go through all these lines one by one,
var myImage = new Image();
This line creates an Image object which in turn is a property of a Document object. We will see the Document object in the following steps. This image object is used for holding a bitmap image which is accessed by a provided path. The path is provided using the Image object’s property called “src” i.e. source as shown in the second line, as
myImage.src = “GraphicManiaLogo.png”;
Though I am picking a local image file for simplicity, you can pick any image from the internet by specifying the URL for that image.
Third line,
var canvas = null;
We will use this variable to refer to our canvas which we have created in the HTML file.
var context2D = null;
This variable will refer to the “getContext()” method of the canvas element. We will see it soon.
Step8. Accessing HTML5 Canvas with Java Script
Let us continue with our Java Script. Our very first job is to access the canvas element. For that we will create an “init()” function as shown below,
window.onLoad = init;
function init()
{
canvas = document.getElementById(‘MyCanvas’);
}
We will see what the above lines are doing.
window.onLoad = init;
It is a global event handler for a load event of a browser window. (See that Java Script can listen to your browser window events.)
This event is fired when all document objects are in the DOM (Document Object Model) and all images are completely loaded, which ensures that we will only have access to our objects when they are completely available, thus preventing any preloading errors. For more information on DOM follow http://www.w3.org/DOM/
As a global event handler, it needs a function call (also known as handler function). In our case “init” is the handler function and it is called when load event is fired.
Thus, statements inside this function are executed. In our case the statement is as follows,
canvas = document.getElementById(‘MyCanvas’);
“document” refers to the container of the HTML document, which further gives access to HTML objects like TITLE, HEAD, BODY etc. This will allow getting the “id” attributes specified in HTML tags. In our case we have put the “id” attribute inside the canvas tag.
As the name suggests, the “getElementById” refers to specified “id”. Here we have specified exactly the same name “MyCanvas”, which is assigned to the attribute, id =”MyCanvas” in the HTML file.
The whole thing is assigned to a canvas variable. Thus we are accessing the HTML5 canvas via Java Script.
The final script up to this stage is as shown below,
var myImage = new Image();
myImage.src = “GraphicManiaLogo.png”;
var canvas = null;
var context2D = null;
window.onload = init;
function init()
{
canvas = document.getElementById(‘MyCanvas’);
}
Step9. Accessing Java Script through HTML document
If you think that we can now access the canvas after executing the “init” function in the above steps, then you are partially correct. But we only have one-way communication. i.e. from Java Script to HTML. What about HTML to Java Script? In our HTML file there has to be some link to this “DrawImage.js” file.
In the HTML document there is a <script> tag in which we can specify the type and url of the script as shown,
<script type = “text/javascript” src = “DrawImage.js” > </script>
So our final HTML will look like the one below,
<script type=”text/javascript” src=”DrawImage.js”></script>
<canvas id = “MyCanvas” width = “500” height = “300” style = “border:1px solid” > </canvas>
Now the bridge is complete. We can access the canvas element and its properties. If you want to test the effect, let’s modify the canvas width through Java Script so the modified “init” function will look like this,
function init()
{
canvas = document.getElementById(‘MyCanvas’);
canvas.width = 150;
}
After testing the different values for canvas width, remove this whole line,
canavs.width = 150;
Since we have already set the width in the HTML file.
Step10. Setting up a complete HTML5 file
Since our HTML file now is in the final stage for this tutorial, we will convert it into a standard HTML5 file.
I kept it simple for better understanding. But now let us see it in perfect form. To create the HTML5 document, the first line must be like the one below,
<!DOCTYPE HTML>
Then we will add standard HTML tags like Title and Body and our final HTML will look like this,
<!DOCTYPE HTML>
<html>
<head>
<title>Introduction to HTML5 canvas element.</title>
<script type=”text/javascript” src=”DrawImage.js”></script>
</head>
<body>
<p>Introduction to HTML5 canvas element along with Java Script</p>
<canvas id = “MyCanvas” width = “500” height = “300” style=”border:1px solid”>
<p>Looks like your browser does not support the canvas element.</p>
</canvas>
</body>
</html>
Observe that our <script> tag is inside the <head> tag and the <canvas> tag is inside the <body> tag. And also, the observe <p> tag is inside the <canvas> tag. It will display the message in the browser if the user’s browser does not support HTML5 or some of the HTML5 features. The rest is standard HTML form which we have been using for long time.
Save this “MyCanvas.html” file after making all the above changes. This is our final HTML file for the tutorial. The remaining parts are all in Java Script. So let us concentrate again on our “DrawImage.js” file.
Step11. “getContext(‘2d’)
The canvas itself does not draw graphics. It has a function called “getContext()”, which renders the graphics over a canvas. We might need to render either “2d” or “3d” context. So we may have,
canvas.getContext(‘2d’);
canvas.getContext(‘3d’);
Now, “3d” context is not officially available in HTML5. Though it is in early stage, it will surely evolve in the future. If you want to add “3d” context then you will have to see “WebGL” as a third-party solution. It is a royalty-free cross-platform API based on OpenGL ES 2.0, but we are not going to discuss “3d” context in this tutorial. Our focus is on “2d” context. So inside the “init()” function, we will put,
context2D = canvas.getContext(‘2d’);
Now, our modified “init” function will look like the one shown below,
function init()
{
canvas = document.getElementById(‘MyCanvas’);
context2D = canvas.getContext(‘2d’);
}
Ok, now we have both the canvas and the 2d context. It’s time to draw something on it.
Step12. Drawing graphics on a canvas
To draw graphics on the canvas we will create a user defined function and name it “draw()”. Further we will call this function inside the “init()” function.
Inside this new “draw()” function we will put the following line,
context2D.drawImage(myImage, 0, 0);
So put a new “draw()” function in our “DrawImage.js” as shown below,
function draw()
{
context2D.drawImage(myImage,0,0);
}
Also, call this function inside the “init()” function. So our modified “init()” function will look like this,
function init()
{
canvas = document.getElementById(‘MyCanvas’);
context2D = canvas.getContext(‘2d’);
draw();
}
If everything is perfect then you will have the image loaded at the top left corner after opening “MyCanvas.html” in your browser. As the name suggests, the “drawImage(arg1,arg2,arg3)” method is used for drawing an image on a canvas.
For more info on drawImage(), follow http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#images
It takes a minimum of 3 and a maximum of 9 parameters. We have provided 3 parameters. The rest of the parameters are for width, height and scaling.
arg1 = myImage; // It’s an Image Object which holds a specified image
arg2 = 0; // It is the x position of an image on a canvas.
arg3 = 0; // It is the y position of an image on a canvas.
With these values the image will be placed at the top left corner.
Step13. Animating graphics on a canvas
Java Script can call the “setInterval()” method of a window object (in the DOM). This “setInterval()” method can be used to simulate animation. How?
setInterval ( someFunction, delay );
This function takes 2 arguments.
arg1 = someFunction.
This can be any function you want to call repeatedly, depending on the interval set in the second argument.
arg2 = delay.
This specifies an interval in millisecond. (e.g. 1000 millisec = 1 sec) But the question still arises, how we will use this function in our example? How about putting our “draw()” function inside setInterval with a delay of 1000 millisec?
setInterval ( draw, 1000 );
Even this does not make sense, because our draw function currently is set to render an image on the canvas at a fixed position. This will draw the same image again and again in the same position. So what is the fun in doing such stupid things?
We are close to being puzzled now. So instead of drawing on the same position we will continuously change the position over period of time. So we will have to modify our “draw()” function so that it will change and update the position of the image repeatedly.
Before modifying the “draw()” function, first we will modify the “init()” function to put a “draw()” function inside the “setInterval()” method. So the modified “init()” function will look like the one shown below,
function init()
{
canvas = document.getElementById(‘MyCanvas’);
context2D = canvas.getContext(‘2d’);
setInterval(draw, 1000);
}
Now we will declare three new variables, the first is for speed and other two will hold the x and y positions respectively,
var speed = 1;
var x = speed;
var y = speed;
Then we will modify the “draw()” function as shown,
function draw()
{
context2D.drawImage(myImage,x,y);
x += speed; //move towards positive x axis
y += speed; //move towards positive y axis
}
Step14. Clearing the canvas with clearRect() method
At this stage if you open “MyCanvas.html” you will see that after every 1 sec the image is moving in the positive x direction and the positive y direction, but it leaves behind its copy creating a trail.
Why are copies of the image created? Since we are calling the “draw()” function after every 1 second using the “setInterval()” method, each statement inside the “draw()” function is executed. And thus, the “drawImage()” function is also executed every 1 sec creating a copy of the image.
So to fix this we will use the “clearRect()” method. This method clears pixels rendered on context2D object.
We will again modify the “draw()” method to add a clearRect() method as the very first line as shown below,
function draw()
{
context2D.clearRect(0, 0, canvas.width, canvas.height);
context2D.drawImage(myImage,x,y);
x += speed; //move towards positive x axis
y += speed; //move towards positive y axis
}
Now open our “MyCanvas.html” and see how the fix is applied. The image does not make any copies now.
The “clearRect(arg1, arg2, arg3, arg4)” takes four arguments.
arg1 = the x coordinate of this rectangle related to the canvas.
arg2 = the y coordinate of this rectangle related to the canvas.
We put “0” for both values to relate to the upper left corner of the canvas.
arg3 = the width of this rectangle related to the canvas.
arg4 = the height of this rectangle related to the canvas.
We passed the same width and height of the canvas to this rectangle to remove all pixels rendered on the canvas.
Step 15. Improving the animation
Our animation needs an improvement. It appears jerky as we are running it at 1 frame per second (we put 1000 millisecond i.e. 1 sec as interval). To smooth the animation simply put 30 instead of 1000 and observe the animation. Try using different values for delay.
If you want you can create a new variable as var fps = 30. And then as an interval value put 1000/fps.
Our image currently travels beyond the canvas area. We will also fix this by defining the boundaries equal to our canvas. We can directly specify the left edge as 0 and the top edge as 0, since x = 0 and y = 0.
But we must calculate the right edge and the bottom edge. For that we will declare two variables,
var rightEdge;
var bottomEdge;
Now what to do with these variables? We assign values to these variables but inside the “init()” function, since we need the width and height of the canvas. So the modified “init()” function will look like the one shown below,
function init()
{
canvas = document.getElementById(‘MyCanvas’);
context2D = canvas.getContext(‘2d’);
rightEdge = canvas.width – myImage.width;
bottomEdge = canvas.height – myImage.height;
setInterval(draw, 30);
}
Whenever the image hits the edge it must start travelling in the opposite x direction, and when it hits the bottom edge it must start travelling in the opposite y direction. So to change these directions we need two variables as shown,
var xDir = 1;
var yDir = 1;
Now we can easily revert the direction by setting the value as “-1” and multiplying with speed. Hence, 1 is for forward direction and -1 is for backward direction. So we will modify the “init()” function as shown below,
function draw()
{
context2D.clearRect(0, 0, canvas.width, canvas.height);
context2D.drawImage(myImage,x,y);
x += (speed * xDir);
y += (speed * yDir);
}
Multiplication will allow us to reverse the direction by simply multiplying by -1 or 1.
But we still need to set the mechanism which will change the values of “xDir” and “yDir” from 1 to -1 and -1 to 1 depending on the canvas edge and axis. Therefore, we will again modify the “init()” function as shown below,
function draw()
{
context2D.clearRect(0, 0, canvas.width, canvas.height);
context2D.drawImage(myImage,x,y);
x += (speed * xDir);
y += (speed * yDir);
if (x >= rightEdge)
{
x = rightEdge;
xDir = -1; // reverse x direction
}
else if (x <= 0)
{
x = 0;
xDir = 1; // forward x direction
}
if (y >= bottomEdge)
{
y = bottomEdge;
yDir = -1; // reverse y direction
}
else if (y <= 0)
{
y = 0;
yDir = 1; // forward y direction
}
}
Observe how we are checking for “rightEdge” and reversing the “xDir”. Similarly, we are checking for “bottomEdge” and reversing the “yDir”.
Open “MyCanvas.html” in your browser and see how the image is moving from one edge to the other, it’s a really nice effect.
So friends, that’s all for now. See you soon with a new topic. Have a nice time.
Conclusion:
In this article our focus was on using the HTML5 canvas to render an animated image. For that we have used Java Script. We ignored writing Java Script directly into the HTML file, instead we kept it as a separate entity, because this is what we always need for large, professional projects.
Being more collective, the points we have covered were the following:
1) HTML5 canvas and attributes like (id, width, height, style).
2) Accessing Java Script using <script> tag.
3) canvas.getContext(‘2d’) and functions like (drawImage(), clearRect()).
4) Animation using “window.setInterval()” method.
[amember_protect guests_only]If you are already a Premium Member then just sign in and you can download source file for this tutorial.
Not a member? Sign up today or read more about our Premium Member area.
[/amember_protect]
[amember_protect user_action=’hide’ visitor_action=’hide’]
Download the source for this tutorial by clicking the button below:
[/amember_protect]
nice tutorial
JavaScript is one word btw.