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 provided x and y point.
  • Use the lineWidth property 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:

Draw a line on the canvas

Explanation

  • Line 5: We create a canvas element.
  • Lines 7–25: We use a drawLine method 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 canvas element and store it in the canvas variable.
  • Line 27: We use the getContext method to get the 2D rendering context of the canvas.
  • Line 28: We call the drawLine method to draw a line from coordinate (10, 10) to coordinate (100, 100).