HTML5 Canvas Line
Draw Lines
To draw a line using HTML5 Canvas is simple, just like draw a line on a paper, define a path, and then fill the path. See the following steps :
- Resets the current path using beginPath() method.
- Let move the drawing cursor to start point to create a new subpath using moveTo(x,y) method.
- Now use lineTo(x, y) method, which adds a new point and connects this point to the starting point by using a straight line.
- Both the above methods accept x and y parameters which tell it exactly where you want to draw the line.
- Finally use stroke() method to make the line visible.
Pictorial Presentation:

Example : Draw a simple Line
The following code will draw a simple line from (10,45) to (180,40).
Output :

Example : Draw horizontal and vertical lines
The following code example uses the moveTo and lineTo methods to incrementally draw horizontal and vertical lines across the canvas.
Output:

Line width
The lineWidth property gives the width (in pixels) of lines. The property value is a positive number (default value 1). On setting, zero, negative, and NaN values must be ignored, leaving the value unchanged. The following example draws a series of lines by using increasing values (1 to 12) for the lineWidth property.
Output:

Color Lines
To draw color lines you can use strokeStyle property, the default color is black. Syntax of the property is object.strokeStyle = color. Here is an example :

Line Cap
lineCap property is used to gets or sets the current line cap style. There are three cap styles :
- butt : Default. A flat edge is put perpendicular to each end of the line with no cap added.
- round : A semicircle or rounded end cap is added to each end of the line.
- square : A square end cap is added to each end of the line.
Here is an example :
Output :

Line Join
lineJoin property is used to get or set the type of corner that is created when two lines join. There are three values :
- bevel : A filled triangle connects the two lines that are joined, creating a beveled corner.
- round : Lines join with a rounded corner.
- square : Default. Lines join with a smoothly mitered corner.
Here is an example :
Output :

Previous: HTML5 Canvas Tutorial
Next:
HTML5 Canvas arcs tutorial
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics