Home » Tutorials » Game Development » HTML5 Canvas For Absolute Beginners – Part 2

HTML5 Canvas For Absolute Beginners – Part 2

HTML5 Canvas For Absolute Beginners – Part 2

Welcome to the second part of the ‘HTML5 Canvas for Absolute Beginners’. In this tutorial, we will continue to describe some of the advanced canvas functions such as draw a shape with line, change color and line width. If you haven’t already, be sure to read the part 1 of this series first!

Drawing Paths

Aside from rectangles, you can make other shapes by using paths with several canvas functions such as:

  • beginPath() – This function have to be called every time when starts a new path.
  • moveTo() – Set and move your starting point.
  • lineTo() – Draws a straight path from the previous point that defined in the moveTo() or last point that drawn by lineTo().
  • closePath() – Close path by connecting the last point with the first point.
  • stroke() – Fill the outline of the path.
  • fill() – Fill the path with color.

Easy to understand right? Besides, there is one more thing you need to know before we start the tutorial which is every shape that you make must consists of at least 3 points as shown below:

HTML5 Canvas beginPath

Ok, let’s start to create a path with ‘beginPath‘ function follow with ‘moveTo‘, ‘lineTo‘, ‘closePath‘ and ‘fill‘ functions. Open up your previous HTML document and try to insert all these functions into your code as shown below:

<!DOCTYPE html>
<html>
	<head>
		<title>HTML5 Canvas For Absolute Beginners | onlyWebPro.com</title>
        <script type="text/javascript">
			function drawShape() {
				var myCanvas = document.getElementById("myCanvas");
				var ctx = myCanvas.getContext("2d");
				ctx.beginPath();
				ctx.moveTo(75,0);
				ctx.lineTo(150,100);
				ctx.lineTo(0,100);
				ctx.closePath();
				ctx.fill();
			}
		</script>
	</head>

	<body onLoad="drawShape()">
		<canvas id="myCanvas" width="300" height="300">
			<!-- Insert fallback content here -->
            Sorry, your browser doesn't support canvas technology
		</canvas>
	</body>
</html>

Save the code and run it on your browser, you should see a black triangle appeared on your page as shown below:

Use HTML5 Canvas To Draw A Triangle

Simple right? Let’s create some others shape such as diamond with path. In order to create a diamond shape from triangle, you have to add a new point at the bottom that can connect with the second and the third points. In this case , the first point is located at (75,0), second point is located at (150, 100) and the third point is located at (0,100) as shown below:

HTML5 Canvas To Create Diamond

So our new point must have a same x-axis (75) value with the first point but different y-axis (200) value from others. Try to insert the following code before your last current lineTo function, to create a new bottom point:

ctx.lineTo(75, 200);

Save your code and run it, you should see a diamond shape appeared, instead of a triangle. Cool right? You can use the same concept to draw any other complicated shape that you want, but for drawing arc or circles we use ‘arc‘ function. We will discuss the ‘arc‘ function in next tutorial, because ‘arc‘ function is little more complex than the one we have seen above.

Change Color and Line Width

So far everything that we created has been filled in black. Let’s customize it by using ‘fillStyle‘, ‘lineWidth‘ and ‘strokeStyle ‘ functions.

  • fillStyle – Fill shape with rgb colors
  • lineWidth – Set width of outline of the shape
  • strokeStyle – Fill shape outline with rgb color

Let’s try to fill the shape that we created just now with green, 1px width of outline and fill the outline with blue.

ctx.fillStyle = "rgb(102, 204, 0)"; //filled green for inner content
ctx.lineWidth = 1; // 1px width of outline
ctx.strokeStyle = "rgb(0, 50, 200)"; //filled red for outline

ctx.closePath(); 

//Fill the shape with colors that defined above
ctx.fill();
ctx.stroke();

Preview it on your browser and you diamond shape should look like the following picture:

HTML5 Canvas Diamond Shape

Note: You must call ‘closePath‘ function before you fill the shape with any colors, else your shape will has missing outline for the last point as shown below:

HTML5 Canvas Missing Outline

Final Code

<!DOCTYPE html>
<html>
	<head>
		<title>HTML5 Canvas For Absolute Beginners | onlyWebPro.com</title>
        <script type="text/javascript">
			function drawShape() {
				var myCanvas = document.getElementById("myCanvas");
				var ctx = myCanvas.getContext("2d");
				
				//Begin our drawing
				ctx.beginPath();
				ctx.moveTo(75,0);
				ctx.lineTo(150,100);
				ctx.lineTo(75, 200);
				ctx.lineTo(0,100);
				
				//Define the style of the shape
				ctx.lineWidth = 1;
				ctx.fillStyle = "rgb(102, 204, 0)";
				ctx.strokeStyle = "rgb(0, 50, 200)";
				
				//Close the path
				ctx.closePath(); 
				
				//Fill the path with ourline and color
				ctx.fill();
				ctx.stroke();
				
			}
		</script>
	</head>

	<body onLoad="drawShape()">
		<canvas id="myCanvas" width="300" height="300">
			<!-- Insert fallback content here -->
            Sorry, your browser doesn't support canvas technology
		</canvas>
	</body>
</html>

In next tutorial, we will describe more other functions that can be used for canvas element. Stay tune!

Other HTML5 and CSS3 tutorial


Android, iOS Development Tutorials