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>
<html>
<head>
<style>
#test {
width: 180px;
height: 40px;
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(70,70,50,0,Math.PI*2,true);
// Outer circle
ctx.moveTo(115,75);
ctx.arc(70,75,35,0,Math.PI,false)
ctx.lineTo(25,75,35,70);
ctx.moveTo(60,60);
ctx.arc(55,60,5,0,Math.PI*2,true);
// Left eye
ctx.moveTo(90,60);
ctx.arc(85,60,5,0,Math.PI*2,true);
// Right eye
ctx.stroke();
} else {
alert('You need Safari or Firefox 1.5+ to see this
output.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
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 |