To draw canvas on a web page, use the HTML5 canvas element. The <canvas> element allows you to draw graphics using JavaScript. With canvas, draw a line, rectangle, Bezier curves, etc.
Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.
With that, you also need set an id for canvas as shown in the below code snippet −
<canvas id = "newCanvas" width = "100" height = "100"></canvas>
Find that <canvas> element in the DOM using getElementById() method −
var canvas = document.getElementById("newCanvas");
To display something on canvas, a script first needs to access the rendering context and draw on it. The <canvas> has a DOM method called getContext to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context2d.
Let us now see an example to draw paths in HTML5 with <canvas> −
Example
<!DOCTYPE HTML> <html> <head> <style> #test { width: 100px; height:100px; margin: 0px auto; background-color: orange; } </style> <script> function drawShape() { // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Draw shapes ctx.beginPath(); ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle ctx.moveTo(110,75); ctx.arc(75,75,35,0,Math.PI,false); // Mouth ctx.moveTo(65,65); ctx.arc(60,65,5,0,Math.PI*2,true); // Left eye ctx.moveTo(95,65); ctx.arc(90,65,5,0,Math.PI*2,true); // Right eye ctx.stroke(); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body id = "test" onload = "drawShape();"> <canvas id = "mycanvas"></canvas> </body> </html>
Output
This will produce the following output −
Let us see another example to draw a quadratic curve in HTML5 −
Example
<!DOCTYPE HTML> <html> <head> <style> #test { width: 100px; height:100px; margin: 0px auto; } </style> <script type> function drawShape() { // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); // Draw shapes ctx.beginPath(); ctx.moveTo(75,25); ctx.quadraticCurveTo(25,25,25,62.5); ctx.quadraticCurveTo(25,100,50,100); ctx.quadraticCurveTo(50,120,30,125); ctx.quadraticCurveTo(60,120,65,100); ctx.quadraticCurveTo(125,100,125,62.5); ctx.quadraticCurveTo(125,25,75,25); ctx.stroke(); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body id = "test" onload = "drawShape();"> <canvas id = "mycanvas"></canvas> </body> </html>
Output
This will produce the following output −