• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Canvas Tag in HTML5

July 31, 2011 //  by Krishna Srinivasan//  Leave a Comment

Introduction

HTML5 is the version of HTML and XHTML that has rekindled the future of HTML and is treated as the future of the web technology. HTML5 originated with the cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG) and has the capability to address the increasing RIA demands. The new features like canvas, video, audio, local storage, web worker, web sockets etc have given HTML5 a real push in the market.

As HTML5 is still developing in leaps and bounce, support is still not available for the advanced features in certain browsers. Though modern browsers support most of the features, google chrome is the best among the available. The alarming issue yet to be resolved is the lack of support for HTML5 features in IE. It is expected that in the next release of the IE, more features will be supported.

Canvas

Canvas is one of the most discussed additions in HTML5.This feature allows to create dynamic effects in web pages without any external plug-in. Canvas creates a 2d drawing area where, images can be added, build graph, create animation etc using JavaScript functionality. Canvas tag is supported in all major browsers like Mozilla, Chrome, Safari, Opera etc

<Canvas> Element

Canvas element creates a rectangular portion in the webpage with co-ordinate system. Canvas element, like any other HTML5 element has DOM structure with its specific id attribute. There can be more than one canvas tag in a page. Each Canvas element can be clearly differentiated using id attribute. JavaScript should be used to draw images or build animation on Canvas.

Canvas element without any associated JavaScript code is completely empty. It does not have any border or content of its own.

1
<canvas id=“demoCanvas” width=“200” height=“200”></canvas>

<canvas id=“demoCanvas” width=“200” height=“200”></canvas>

Canvas is a container tag with three attributes. ‘Width’ and ‘Height’ attributes are used to fix the size of the available drawing area created by the element. Like any other element in HTML canvas also has the ‘ID’ attribute, which can be used to access the element using scripting language. All the attributes are optional and width and height can be set using DOM properties. If the size of the canvas is not set, it will occupy a default width of 300 pixels and height of 150 pixels. The text between the starting tag and end tag of canvas will be displayed on the browser if the browser does not support Canvas.

Rendering Context

The drawing surface canvas creates has one or more rendering context associated within and can be used for creating and manipulating the contents in canvas. Presently only 2d drawing context is available as 3d rendering context is still in experimental stages. Scripting languages should be used to access the context in order to draw on it. Rendering context of the canvas element can be accessed using the DOM method known as getContext().

1
2
var canvas = document.getElementById(‘demoCanvas’);  // get canvas DOM node 
	var ctx = canvas.getContext('2d');  //to access the drawing context

var canvas = document.getElementById(‘demoCanvas’); // get canvas DOM node var ctx = canvas.getContext('2d'); //to access the drawing context

The canvas DOM node can be retrieved using the JavaScript method getElemntById(). Once the Canvas element is accessed, using the getContext() method the drawing context is accessed. The method getContext takes a parameter of type context. In the above example ‘2d’ drawing context has been accessed.

The complete code of a sample HTML5 page using canvas is shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
	<head>
		<title>Canvas</title>
		<script type="text/javascript">
		function draw() {
			var canvas = document.getElementById("demoCanvas");
			if (canvas.getContext){
				var ctx = canvas.getContext('2d');
			} else {
				alert('Your browser does not support canvas!!');
			}
		}
		</script>
	</head>
	<body onload="draw()">
		<canvas id="demoCanvas" width="300" height="225“ ></canvas>
	</body>
	</html>

<html> <head> <title>Canvas</title> <script type="text/javascript"> function draw() { var canvas = document.getElementById("demoCanvas"); if (canvas.getContext){ var ctx = canvas.getContext('2d'); } else { alert('Your browser does not support canvas!!'); } } </script> </head> <body onload="draw()"> <canvas id="demoCanvas" width="300" height="225“ ></canvas> </body> </html>

Drawing Shapes

Canvas is a two dimensional grid with the values of ‘X’ axis increasing towards the right and the values of ‘Y’ axis increasing towards the bottom edge. The co-ordinate points are used to position while drawing objects on the canvas. Rectangle is the only shape that can be drawn on the canvas. All other shapes are created through a combination in canvas. There are three different functions available for drawing rectangles.

1
2
3
fillRect(x,y,width,height) // Draws a filled rectangle from the specified coordinates
	strokeRect(x,y,width,height) // Draws a rectangular outline from the specified coordinates
	clearRect(x,y,width,height)  //Clears the specified area

fillRect(x,y,width,height) // Draws a filled rectangle from the specified coordinates strokeRect(x,y,width,height) // Draws a rectangular outline from the specified coordinates clearRect(x,y,width,height) //Clears the specified area

All the three methods have four parameters, namely

  • X – x coordinate relative to origin
  • Y – y coordinate relative to origin
  • Width – width of the rectangle
  • Height – height of the rectangle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<head>
		<script type="text/javascript">
		function draw() {
			var canvas = document.getElementById("demoCanvas");
			if (canvas.getContext){
				var ctx = canvas.getContext('2d');
				ctx.fillRect(20,20,75,75);
				ctx.clearRect(40,40,50,50);
				ctx.strokeRect(10,10,100,100);
			} else {
				alert('Your browser does not support canvas!!');
			}
		}
		</script>
	</head>
	<body onload="draw()">
		<canvas id="demoCanvas" width="300" height="225“style="border; 5px green dashed" ></ canvas>
	</body>

<head> <script type="text/javascript"> function draw() { var canvas = document.getElementById("demoCanvas"); if (canvas.getContext){ var ctx = canvas.getContext('2d'); ctx.fillRect(20,20,75,75); ctx.clearRect(40,40,50,50); ctx.strokeRect(10,10,100,100); } else { alert('Your browser does not support canvas!!'); } } </script> </head> <body onload="draw()"> <canvas id="demoCanvas" width="300" height="225“style="border; 5px green dashed" ></ canvas> </body>

Different types of path can be drawn in order to obtain complex shapes other than rectangle. The available functions are:-

  • beginPath()
    • beginPath() starts a new path or fresh path on the canvas.
  • closePath()
    • The method is used to draw a straight line from the starting point to the current point. It tries to close the shape.
  • stroke() and fill()
    • These methods are used to draw shapes on the canvas. stroke() method draws only an outline of the shape and the fill() method paints a solid shape. The two methods can be combined in order to obtain complex shapes.
  • moveTo()
    • This method doesn’t draw anything on the canvas. It is like lifting the pointer from one point to another.
    • The method takes two parameters, the coordinates of the new starting point
    • This method is very useful for drawing complex shapes in order to reach different co-ordinate points on the canvas
  • lineTo()
    • This method is used to draw straight lines
    • The method takes two parameters, the x and y coordinates of the end point of the line. The beginning point of the line will be the ending point of the previously drawn path. moveTo() method can be used to change the starting point to draw lines from different points
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script type="text/javascript">
	function draw() {
		var canvas = document.getElementById("demoCanvas");
		var ctx = canvas.getContext('2d');
		ctx.beginPath();
		ctx.moveTo(40,40);
		ctx.lineTo(100,40);
		ctx.lineTo(40,100);
		ctx.fill();
		ctx.beginPath();
		ctx.moveTo(30,30);
		ctx.lineTo(120,30);
		ctx.lineTo(30,120);
		ctx.lineTo(30,30);
		ctx.stroke();
	}
	</script>
	<body onload="draw()">
		<canvas id="demoCanvas" width="300" height="225“ ></canvas>
	</body>

<script type="text/javascript"> function draw() { var canvas = document.getElementById("demoCanvas"); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(40,40); ctx.lineTo(100,40); ctx.lineTo(40,100); ctx.fill(); ctx.beginPath(); ctx.moveTo(30,30); ctx.lineTo(120,30); ctx.lineTo(30,120); ctx.lineTo(30,30); ctx.stroke(); } </script> <body onload="draw()"> <canvas id="demoCanvas" width="300" height="225“ ></canvas> </body>

  • arc()
    • This method is used to draw circles and curves. This is one of the methods that is used very often to draw shapes on canva.
    • This method takes five parameters:
      • x and y are the coordinates of the circle’s center
      • Radius is the radius of the circle or arc
      • The startAngle and endAngle parameters define the start and end points of the arc ,which are measured from the x axis. Angles in the arc function are measured in radians.
      • The anticlockwise parameter is a Boolean value. If true, the arc is drawn in anticlockwise direction, otherwise in clockwise direction.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
arc(x, y, radius, startAngle, endAngle, anticlockwise);
 
 
	<script type="text/javascript">
	function draw() {
		var canvas = document.getElementById("demoCanvas");
		var ctx = canvas.getContext('2d');
		for (var i=0;i<5;i++){
			for (var j=0;j<5;j++){
				ctx.beginPath();
				ctx.arc(20+j*15,20+i*15,10,0,Math.PI*2,true);
				ctx.stroke();
			}
		}
	}
	</script>
	<body onload="draw()">
		<canvas id="demoCanvas" width="300" height="225“ ></canvas>
	</body>

arc(x, y, radius, startAngle, endAngle, anticlockwise); <script type="text/javascript"> function draw() { var canvas = document.getElementById("demoCanvas"); var ctx = canvas.getContext('2d'); for (var i=0;i<5;i++){ for (var j=0;j<5;j++){ ctx.beginPath(); ctx.arc(20+j*15,20+i*15,10,0,Math.PI*2,true); ctx.stroke(); } } } </script> <body onload="draw()"> <canvas id="demoCanvas" width="300" height="225“ ></canvas> </body>

Colors can be set to different shapes in canvas using fillStyle() and strokeStyle() methods. fillStyle() is used to fill a shape with a specific colour and strokeStyle() to draw a border. Both fillStyle and strokeStyle have black as default value, if no colour is set.

1
2
3
4
//colour can be set in the following ways:
	ctx.fillStyle = “Red";  
	ctx.fillStyle = "#FFA810";  
	ctx.fillStyle = "rgb(205,0, 185)";

//colour can be set in the following ways: ctx.fillStyle = “Red"; ctx.fillStyle = "#FFA810"; ctx.fillStyle = "rgb(205,0, 185)";

Images in Canvas

Canvas is a holding area even for images. Images can be added to any co-ordinate position on the canvas. drawImage() method is used to draw the image on the canvas at the specified coordinates using the co-ordinate system . The image object is created and passed as a parameter to the drawImage() method.

1
2
3
4
5
6
7
8
9
10
11
<script type="text/javascript">
	function draw() {
		var canvas = document.getElementById("demoCanvas");
		var ctx = canvas.getContext('2d');
		var cat = new Image();
		cat.src = "car.png“;
		ctx.drawImage(cat,50,50);
	</script>
	<body onload="draw()">
		<canvas id="demoCanvas" width="300" height="225“ ></canvas>
	</body>

<script type="text/javascript"> function draw() { var canvas = document.getElementById("demoCanvas"); var ctx = canvas.getContext('2d'); var cat = new Image(); cat.src = "car.png“; ctx.drawImage(cat,50,50); </script> <body onload="draw()"> <canvas id="demoCanvas" width="300" height="225“ ></canvas> </body>

Conclusion

Canvas tag can be used to design games and complex dynamic effects in HTML5. In near future, with the canvas extending its support to 3d context drawing more and more dynamic effects can be generated. Presently there are games and websites which have made use of canvas extensively.

Category: HTMLTag: HTML5

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « Location tracker in Android using GPS positioning and SQLite
Next Post: The Most Popular Collaborative Models »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact