JavaScript Canvas  Basic Paths 
Written by Ian Elliot  
Monday, 02 December 2019  
Page 3 of 3
If you change the arc call to: path1.arc(x, y, r, 0, Math.PI/2); which draws a quarter of a circle, you can see the lines drawn to the start and end points:
If you want the circle to be a subpath disconnected from any other subpath then use a moveTo the start point and a moveTo the start of the next subpath. For example, adding two moveTo calls creates three subpaths – two lines and the quadrant: var path1 = new Path2D(); var x = 200; var y = 200; var r = 100; path1.moveTo(100, 150); path1.lineTo(150, 300); path1.moveTo(300, 200); path1.arc(x, y, r, 0, Math.PI / 2); path1.moveTo(200, 200); path1.lineTo(400, 400); ctx.stroke(path1); Finally, notice that any arc that you draw isn’t closed. You can close it using the closePath function. For example: var path1 = new Path2D(); var x = 200; var y = 200; var r = 100; path1.arc(x, y, r, 0, Math.PI / 2); path1.closePath(); ctx.stroke(path1); which closes the quarter circle to give: If you were expecting a more traditional closed quadrant then to achieve this you need to add some lines from the start and end to the center of the circle: var path1 = new Path2D(); var x = 200; var y = 200; var r = 100; path1.moveTo(x,y); path1.arc(x, y, r, 0, Math.PI / 2); path1.lineTo(x,y); ctx.stroke(path1); which produces: EllipseThe ellipse function is a generalization of the arc function. It draws part of an ellipse as specified by start and stop angles as in the case of the arc function. The difference is that you can now specify a horizontal and a vertical radius and a rotation angle: ellipse(x,y,rx,ry,rot,start angle, stop angle, This draws an ellipse centered on x,y with horizontal radius rx and vertical radius ry. The start angle, stop angle and direction parameters work in the same way as in the arc function. The rot parameter rotates the entire ellipse so that you can draw something more general. For example: path1.ellipse(300,200,150,50,0,0,Math.PI*2);
In this case the rotation angle is zero so the horizontal and vertical radii are in their default orientation. If we specify a rotation angle of 45 degrees: path1.ellipse(300,200,150,50,Math.PI/4,0,Math.PI*2); The x radius is tilted at 45 degrees:
The only other thing to be aware of is that ellipse continues the current path. A line will be drawn from the current position to the starting point of the ellipse and the final point becomes the starting point of the rest of the path. In chapter but not in this extract
Summary
Now available as a paperback or ebook from Amazon.JavaScript Bitmap Graphics


Last Updated ( Monday, 02 December 2019 ) 