HTML5 Canvas - Using Canvas in HTML5

By: Emiley J Emailed: 1786 times Printed: 2623 times    

HTML5 introduces the new <Canvas> tag that lets you draw paths, boxes, circles, characters, and adding images onto a webpage. In fact you can use Canvas to draw graphics on the fly on a webpage. The Canvas tag works hand-in-hand with JavaScript to do the actual drawing. Here's a simple code that shows how you do this.

<canvas id="myCanvas" width="200" height="100"></canvas>

The above code just tells the browser to reserve that space with that size for a canvas and the canvas itself is empty. You need to use JavaScript to actuall draw within that space. The below JavaScript for example draws a simple line within the canvas.

<script>
var c=document.getElementById("myCanvas");
var mcontext=c.getContext("2d");
mcontext.moveTo(0,0);
mcontext.lineTo(300,150);
mcontext.stroke();
</script>

What you have done is to get a handle to the canvas by using its id 'mycanvas', then getting a context to it to run commands on it. The getContext("2d") object is a built-in HTML5 object, with many properties and methods for drawing paths, boxes, circles, text, images, and more. In the above example we just drew a line across the canvas. The output of which will be like this.

Draw a line using canvas in html5

You can do lots of other things with the canvas for example,

To draw a rectangle in Red.

<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
</script>

To draw a circle

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

To draw some text

<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.fillText("I Love Java Samples",10,50);
ctx.stroke();
</script>

To draw a gradient

<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d"); // Create gradient
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"brown");
grd.addColorStop(1,"white"); // Fill with gradient
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);
</script>

Most Viewed Articles (in HTML5 )

Latest Articles (in HTML5)

Comment on this tutorial