Page 1 of 1

HTML 5.0 Canvas Tag and Javascript Tutorial Basic intro to the canvas tag and some javascript features Rate Topic: -----

#1 psyking  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 20
  • View blog
  • Posts: 165
  • Joined: 17-January 10

Posted 01 February 2010 - 01:44 AM

Hey everybody,
I was reading the post in "Request a Tutorial" in the Javascript part of the forum and I read that someone wanted a tutorial on how to use the canvas tag using some of the javascript functionality. I have written this mostly because I want to help the people who need it, but I also got to learn a little while writing this. :D :^:

Which is better?
Is drawing an image in a software and then using the image tag to post it to your site better? Or is using the canvas tag to draw images to your site better? It depends on the person making the page.
The benefits of the software:
  • Easier to make the image, as you can see it while drawing it.
  • Hardly any knowledge of code needed.
The benefits of using the canvas tag are:
  • Games can be made using the canvas tag
  • Can load slightly faster than the image tag
  • Knowledge of HTML and Javascript is increased
  • Can load pre-drawn images, like the <img> tag

Requirements:
  • Basic HTML skills
  • Intermediate knowledge of Javascript
  • Little knowledge of jQuery

What are you going to learn?
You are going to learn the basics of the canvas:
  • How to make a canvas object
  • How to check to see if the browser accepts the canvas tag
  • How to draw basic shapes on the canvas

Canvas Info
Although the canvas can be used to draw 3-d images, for this tutorial, we will only be using the canvas as though it is just like a basic cartesian graph (only has the coordinates of (x,y)), thus rendering it to 2-d. The canvas can be used to make animations, although after every frame everything has to be redrawn. This can take some time depending on the speed of a persons computer. It can also load predrawn images. Games can be made by using the canvas (although you won't be learning how to make games from this tutorial, there are a couple of good examples from these sites of what can be made with the canvas: Gradius-JS, Canvas Cape. These are just some examples of things that people have done with a canvas.). The canvas can do a lot of things with the help of a person to code them, however there are a few limitations, the biggest (in my opinion) that you have to redraw an object every time you want it to move.

Pre-Steps to Getting Started
Before we get started, open your favorite HTML editor and start with the basic HTML layout:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	 <head>
		  <title>Canvas Tutorial</title>
	 </head>
	 <body>
	 </body>
</html>
And save it as canvas.html. What the doctype tag is doing is telling the browser which version of HTML we are using. For this tutorial we will be using HTML 5.0.

Getting Started:

Step 1 - Creating the Canvas
Now that we are here, we need to make our canvas. In between the body tags write the following peice of code:
<body>
<canvas id="tutorial" width="300" height="300">Your browser does not support the new HTML tag <canvas></canvas>
</body>
The content of the canvas tag: "Your browser does not support the new HTML tag <canvas>" is the fallback code, this is used when the browser does not support the canvas tag.

Step 2 - Check if the Browser Will Use the Fallback Code even if it Accepts the <canvas> Tag
Now, most browsers like Mozilla Firefox will just ignore the fallback code because they support the use of the end tag. Some browsers, like Apple's Safari, for instance, accept the <canvas> tag, but don't use the end tag </canvas>. When this happens, the fallback code gets used no matter what. We need to fix this so that the fallback code only happens when the <canvas> tag is not accepted by a browser.
First, we will be creating a <div></div> in the body where the fallback tag goes and removing the current fallback tag that we already have. Give the new div an id of "fallback" so that we can later call on it.
<body>
	 <canvas id="tutorial" width="300" height="300"><div id="fallback"></div></canvas>
</body>



The div will show up in Apple's Safari and other browsers like it regardless of the fact that they accept the <canvas> tag. To hide the div from people using these browsers is a fairly simple step. It requires that we use a function from the jQuery library (available here: jQuery. Save it as "jQuery.js" and in the same directory as the HTML file for this tutorial). We will need to put this into the <head> tags. The code we will be using for this is here:
<head>
	 <title>Canvas Tutorial</title>
	 <!-- Load the jQuery library: -->
	 <script type="text/javascript" src="jQuery.js"></script>
	 //Begin our function
	 <script type="text/javascript">
		  //Set the page to hide the div as soon as the page begins to load
		  //The dollar sign ($) is the shortcut for jQuery.
		  //First we need to have this happen when the page is loading, so we call the document.ready function from jQuery's library:
		  $(document).ready(function(){
			   //Select the div we gave the id of "fallback" and tell it to hide:
			   $("#fallback").hide();
		  });
	 </script>
</head>


This code hides the div. However, if the browser does not accept the <canvas> tag, we will need to unhide it. But we only want it unhidden if the browser does not accept the <canvas> tag.

The next step is to check if the browser does accept the tag or not, if it does, the div tag will will stay hidden. If it does not accept the tag, we want to unhide the <div> tag. To do this we will be placing this little Javascript/jQuery code snippet in between the head tags:
<head>
	 <title>Canvas Tutorial</title>
	 <script type="text/javascript" src="jQuery.js"></script>
	 <script type="text/javascript">
		  $(document).ready(function(){
			   $("#fallback").hide();
		  });
	 </script>
	 <script type="text/javascript">
		  //Create a canvas variable for use when the document loads:
		  var canvas;
		  //When the page is loading, we want it to check to see if the page accepts the canvas tag:
		  $(document).ready(function(){
			   //We need to create a variable to make typing easier for us in the long run:
			   canvas = document.getElementById("tutorial");
			   // Now we check to see if the <canvas> tag is accepted in the browser
			   if (canvas.getContext){
					/* Leave this area blank because we won't be doing anything in this area. */
			   }else{
					//This is where we unhide the div.
					$("#fallback").show();
			   }
		  });
	 </script>
</head>


Now, we have made it so that we have our fallback, we are ready to begin adding color to our blank canvas.

Step 3 - The First Rectangle
We are finally ready to begin drawing on our canvas! The first thing we will draw is a rectangle. We will be using some Javascript commands again, this time we will be using them as a function. We will also be using some input buttons placed below the canvas. We will be editing the body sections for this. First, we will add this code:
<script type="text/javascript">
	 //Create the "pen":
	 var pen;
	 $(document).ready(function(){pen=canvas.getContext('2d');});
	 //Create the function to draw the square with the parameters x,y,width,height:
	 function drawRect(x,y,width,height){
		  //Set the color of the "pen":
		  pen.fillStyle="rgb(0,0,0)";
		  //And finally, we draw the rectangle:
		  pen.rect(x,y,width,height);
	 }
</script>


That's all we need for the function, now we move on to making the forms. Add this code below the end of the canvas tag:
<!--Create a form to hold the input fields:-->
<form id="input_fields">
	 <!--Create four text fields, each with different ID's:-->
	 X-Value: <input type="text" id="xval">
	 Y-Value: <input type="text" id="yval">
	 Width: <input type="text" id="wval">
	 Height: <input type="text" id="hval">
	 <!--Create the "Draw" button with the command to draw the rectangle on the canvas:-->
	 <input type="button" value="Draw!" onclick="java script:drawRect(document.getElementById('xval').value,document.getElementById('yval').value,document.getElementById('wval').value,document.getElementById('hval').value);">
<!--Close the form:-->
</form>



The whole code looks like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	 <head>
		  <title>Canvas Tutorial</title>
		  <!-- Load the jQuery library: -->
		  <script type="text/javascript" src="jQuery.js"></script>
		  <!-- Begin our function -->
		  <script type="text/javascript">
			   //Set the page to hide the div as soon as the page begins to load
			   //The dollar sign ($) is the shortcut for jQuery.
			   //First we need to have this happen when the page is loading, so we call the document.ready function from jQuery's library:
			   $(document).ready(function(){
					//Select the div we gave the id of "fallback" and tell it to hide:
					$("#fallback").hide();
			   });
		  </script>
		  <script type="text/javascript">
			   //Create a canvas variable for use when the document loads:
			   var canvas;
			   //When the page is loading, we want it to check to see if the page accepts the canvas tag:
			   $(document).ready(function(){
					//We need to create a variable to make typing easier for us in the long run:
					canvas = document.getElementById("tutorial");
					// Now we check to see if the <canvas> tag is accepted in the browser
					 if (canvas.getContext){
						 /* Leave this area blank because we won't be doing anything in this area. */
					}else{
						//This is where we unhide the div.
						$("#fallback").show();
					}
			 });
	 </script>
	 </head>
	 <body>
		  <canvas id="tutorial" width="300" height="300"><div id="fallback"></div></canvas>
		  <script type="text/javascript">
			   //Create the "pen":
			   var pen;
			   $(document).ready(function(){ pen=canvas.getContext('2d');});
			   //Create the function to draw the square with the parameters x,y,width,height:
			   function drawRect(x,y,width,height){
					//Set the color of the "pen":
					pen.fillStyle="rgb(0,0,0)";
					//And finally, we draw the rectangle:
				   pen.rect(x,y,width,height);
			   }
		  </script>
		  <!--Create a form to hold the input fields:-->
		  <form id="input_fields">
			   <!--Create four text fields, each with different ID's:-->
			   X-Value: <input type="text" id="xval">
			   Y-Value: <input type="text" id="yval">
			   Width: <input type="text" id="wval">
			   Height: <input type="text" id="hval">
			  <!--Create the "Draw" button with the command to draw a rectangle on the canvas:-->
			  <input type="button" value="Draw!" onclick="java script:drawRect(document.getElementById('xval').value,document.getElementById('yval').value,document.getElementById('wval').value,document.getElementById('hval').value);">
		  <!--Close the form:-->
		  </form>
	 </body>
</html>



Save your file and open it in your favorite web browser. Play around with it for a little.

If you don't think that your file is running correctly, try using this one: Attached File  Canvas.zip (43.82K)
Number of downloads: 462 or try switching to a new web browser (the best I think for this would be Mozilla Firefox).


Other Javascript <canvas> Commands
These are some more commands for drawing on the canvas:
arc(x,y,r,start_angle,end_angle,clockwise);
/* The (x,y) coordinates are the center, r is the radius, start_angle
	 is the angle from which the arc starts (between 0 and 360 or 0
	 and 2*PI), end_angle is the angle at which the arc ends 
	 (between 0 and 360 or 0 and 2*PI) and clockwise just tells 
	 which direction to draw the arc (0 = counterclockwise, 1 = clockwise) */

beginPath();
//This starts a path, that usually starts at the origin (0,0)

moveTo(x,y);
//This moves the point you are going to draw to the position (x,y) without drawing a line

lineTo(x,y);
//Uses moveTo(x,y) as the starting point and draws a line to the point (x,y)


Those are some of the ones used most often, I find. For more you can check out some of the websites below.
References:
For a reference of more tags that you can use, you can look at this website which gives an explanation of each command that can be given to the canvas: Canvas Reference
A (better perhaps) tutorial can also be found at the Mozilla Developer Center: Canvas Tutorial
Also, you can check out my own version of this at: Canvas Demo


Note: fixed the comment introducing the jQuery library. Now it won't show up in the web browser.

This post has been edited by psyking: 04 February 2010 - 07:44 PM


Is This A Good Question/Topic? 2
  • +

Replies To: HTML 5.0 Canvas Tag and Javascript Tutorial

#2 Shane Hudson  Icon User is offline

  • D.I.C Technophile
  • member icon

Reputation: 343
  • View blog
  • Posts: 1,286
  • Joined: 06-December 09

Posted 02 February 2010 - 05:33 AM

Very good tutorial, I cannot think of any projects that I need to use this for... but I am sure I will use it one day!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1