How to draw lines on canvas using JavaScript
Overview
The lineTo method is used to draw a line on the canvas. Below are the steps to draw a line on the canvas:
- Use the
beginPath()method to start a new path. - Use the
moveTo(x,y)method to move the drawing cursor to a specific coordinate. - Use the
lineTo(x,y)method to draw a line from the current position to the providedxandypoint. - Use the
lineWidthproperty to set the width of the line. - Use the
stroke()function to add stroke to the given path.
Example
The below code demonstrates how to draw a line on the canvas:
Explanation
- Line 5: We create a
canvaselement. - Lines 7–25: We use a
drawLinemethod that will take the drawing context, line start and end coordinate, stroke color, and line width as arguments. This method will draw a line for the given coordinate. - Line 26: We get the
canvaselement and store it in thecanvasvariable. - Line 27: We use the
getContextmethod to get the 2D rendering context of the canvas. - Line 28: We call the
drawLinemethod to draw a line from coordinate (10,10) to coordinate (100,100).