Summary -

In this topic, we described about the Draw Path with detailed example.

A path contains a list of more or zero subpaths. The canvas paths allow us to draw custom models by using path. There are at least one or more than one points in every subpath that are linked by curves or straight lines.

To draw paths on the canvas we need the following methods -

Method Description
beginPath() This method resets the existing path.
moveTo(x, y) This method establishes a new subpath with the given point.
closePath() This method marks the present subpath as closed and begins a new subpath with a point. i.e. It is same as the beginning of new subpath and ending of the newly closed subpath.
fill() Fills the subpaths with the present fill style.
stroke() Strokes the subpaths with the present stroke style.
arc(x, y, radius, startAngle, endAngle, anticlockwise) Adds points to the subpath such that the arc described by the edge of the circle named by the arguments, starting at the provided start angle and ending at the provided end angle, going in the provided direction. The subpath is added to the path, linked to the previous point by a straight line.

Example -

The below example describes about how to draw a shape using above-mentioned methods.
<!DOCTYPE html>   
            #test {
            width: 180px;
            height: 40px;
            margin: 0px auto;}
   <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
				// Outer circle
				// Left eye
				// Right eye
			} else { 
				alert('You need Safari or Firefox 1.5+ to see this 
  <body id = "test" onload = "drawShape();">
    <canvas id = "mycanvas"></canvas>

Output -

Browser Support

The following browsers with versions in the table indicates the initial browser version that completely supports the path method -

Method Chrome Edge Firefox Safari Opera
Beginpath( ) Yes 9.0 and above Yes Yes Yes