Comment: We can use "path" to draw any graphic. The path is simply a series of points and the lines connecting these points. Any Canvas context will only have one "current path", and when context.save() is called, the "current path" will not be saved
original:?p=371
This article is translated from Steve Fulton & Jeff Fulton HTML5 Canvas, Chapter 2, Using Paths to Create Lines
For HTML5 Canvas, we can use paths to draw any graph. The path is simply a series of points and the lines connecting these points. Any Canvas context will have only one current path, and when context.save() is called, the current path will not be saved.
The beginning and end of the path
Calling beginPath() can start a path, while calling closePath() will end the path. If you connect a point in the path, then this connection forms a subpath. If the last point in the subpath is connected to its first point, we consider that the subpath is closed.
Line drawing
The most basic path operation consists of repeated calls to moveTo() and lineTo() commands. For example, the following example:
function drawScreen() {
context.strokeStyle = "black";
context.lineWidth = 10;
context.lineCap = 'square';
context.beginPath();
context.moveTo(20, 0);
context.lineTo(100, 0);
context.stroke();
context.closePath();
}
In the example above, we depict a horizontal line segment with a width of 10 pixels; at the same time, we also set the lineCap and strokeStyle properties. Here is a list of some commonly used properties:
lineCap
lineCap defines the style at both ends of the line segment in Canvas, and can be set to one of the following three values:
butt. Default value; add straight edges at both ends of the line segment.
round. Add a semicircular line cap at each end of the line segment. The diameter of the line cap is equal to the width of the line segment.
square. Add square line caps to both ends of the line segment. The length of the line cap is equal to the width of the line segment.
lineJoin
lineJoin defines the corner pattern at the intersection of two line segments. The following are three optional values:
miter. Default; creates a sharp corner. You can limit the length of sharp angles by setting the miterLimit property—mitterLimit is the maximum ratio of sharp angle length and line width, and the default is 10.
bevel. Create a bevel.
round. Create a rounded corner.
lineWidth
lineWidth defines the thickness of the line, and the default is 1.0.
strokeStyle
strokeStyle defines the styles such as colors used to render lines.
Translator's note: When lineJoin is set to miter, but the sharp corner length exceeds the limit of miterLimit, Canvas will display the bevel corner effect.