HTML Tutorials for Beginners to Advance

HTML Basic Structure, Elements in HTML, HTML Headlines, List in HTML, Insert Images in Web Pages, Tables in HTML, HTML form design, HTML5 Elements, HTML Canvas, etc.

HTML Canvas


HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations.

Here is a simple <canvas> element which has only two specific attributes width and height plus all the core HTML5 attributes like id, name and class etc.

What is HTML Canvas?

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.

The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.


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

See this example:

<!DOCTYPE HTML>
<html>
<head>
<style>
#mycanvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id="mycanvas" width="100" height="100"></canvas>
</body>
</html>

Output:


The Rendering Context

The <canvas> is initially blank, and to display something, a script first needs to access the rendering context and draw on it.

The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d.

Following is the code to get required context along with a check if your browser supports <canvas> element −

var canvas = document.getElementById("mycanvas");

if (canvas.getContext){
var ctx = canvas.getContext('2d');
// drawing code here
}

else {
// canvas-unsupported code here
}

Browser Support

The latest versions of Firefox, Safari, Chrome and Opera all support for HTML5 Canvas but IE8 does not support canvas natively.

You can use ExplorerCanvas to have canvas support through Internet Explorer. You just need to include this javascript as follows:

<!--[if IE]><script src="excanvas.js"></script><![endif]-->

Canvas Example

Draw a Line

See this example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();

Output:


Draw a Circle

See this example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();

Output:


Draw a Text

See this example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);

Output: