The canvas element is new to HTML5. You can use the canvas to draw lines, shapes, text, and more. To draw a line onto the HTML5 Canvas, we will use various methods. The most common methods used in drawing lines are beginPath(), moveTo(), lineTo(), and stroke().

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

context.beginPath(); context.moveTo(x, y); context.lineTo(x, y); context.stroke();

Example

Your browser does not support the HTML5 canvas tag.

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.

context.lineWidth=number; context.lineCap=“butt|round|square”; context.strokeStyle=color|gradient|pattern;

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.