The beginPath() mehtod is to declare that we want to draw a line. Next is the moveTo(), which is used to position the context point. Then we use the lineTo() method to draw a straight line from the starting point to the new target point. Finally, we use the stroke() method to apply a stroke to the line and make it visible. The default stroke color is black, but we can style the line’s color (strokeStyle) as well as other properties such as width (lineWidth) or cap (lineCap). You should note that Internet Explorer 8 and earlier versions, do not support the element, nor the context properties and/or methods.

Syntax

Example

Line Styling: Width, Color, and Cap

The lineWidth property sets or returns the current line width, and the lineCap property sets or returns the style of the end caps for a line. The strokeStyle property sets or returns the color, gradient, or patterns. Here is an example of how to apply a different width, color, and cap to a line. You should note that the lineCap values of round and square increase the length of the line. The default value is butt.