How to declare a Canvas in HTML5?
Assume in your HTML page you want to draw a graph for area 300 x 250. In this case you can declare a canvas in HTML body part with width 300px & height 250px. Look at the sample below how to declare canvas element in a html document. Always practice to write “Your browser does not support HTML5 Canvas.” in between the canvas tag. This message will show if your browser not supports canvas.
<canvas id="mycanvas" width="300" height="250"> Your browser does not support HTML5 Canvas. </canvas>
How to Draw a rectangle using HTML5 Canvas?
var mycanvas = document.getElementById('mycanvas'); var context = mycanvas.getContext('2d'); context.fillStyle = 'blue'; context.fillRect(20, 20, 80, 80);
While drawing graphics on a html page if required you can have multiple <canvas> elements in a single HTML5 page. Using different ids you can render each individual canvas from Client Scripts.
How to Draw a line using HTML5 Canvas?
var c = document.getElementById("mycanvas"); var ctx = c.getContext("2d"); ctx.moveTo(0,0); ctx.lineTo(200,100); ctx.stroke();
How to Draw a Circle using Canvas element?
To draw a circle using HTML5 Canvas element look at the below example. Here I used Arc() method to draw a circle. HTML5 Canvas Arc() method accepts 6 parameters. Initial 2 parameters are for x & y axis. Third parameter is the radius of Arc. From the below code 0 & 2*Math.PI are the starting & ending angles. Last parameter of a Arc() method is a optional parameter. This param says is the Arc is clockwise or anti-clock wise. This parameter accepts Boolean values.
var c = document.getElementById("mycanvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.arc(95, 50, 40, 0, 2*Math.PI, true); ctx.stroke();
How to print text using HTML5 Canvas?
To draw a text or label using HTML5 Canvas here I used fillText() method. Using font we can set style for our text. In the below example I declared font as “20px Arial”. It means while rendering font-size will show 20px & the font-family is Arial. FillText() method accepts 3 parameters. First one is the text string, I mean which text you want to display on your canvas. Then the 2nd & 3rd parameters says the position of text on Canvas.
var c = document.getElementById("mycanvas"); var ctx = c.getContext("2d"); ctx.font = "20px Arial"; ctx.fillText("Your Name",20,90);