HTML5 Canvas - Drawing Paths



We require the following methods to draw paths on the canvas −

S.No. Method and Description
1

beginPath()

This method resets the current path.

2

moveTo(x, y)

This method creates a new subpath with the given point.

3

closePath()

This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.

4

fill()

This method fills the subpaths with the current fill style.

5

stroke()

This method strokes the subpaths with the current stroke style.

6

arc(x, y, radius, startAngle, endAngle, anticlockwise)

Adds points to the subpath such that the arc described by the circumference of the circle described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction, is added to the path, connected to the previous point by a straight line.

Example

Following is a simple example which makes use of above mentioned methods to draw a shape.

<!DOCTYPE HTML>

<html>
   <head>
   
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      
      <script type = "text/javascript">
         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>

It will produce the following output −

html5_canvas.htm
Advertisements