Lines on HTML Canvas

instance

Your browser does not support the HTML5 canvas tag.
// Create the canvas:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Define a new path:
ctx.beginPath();
// Define the starting point:
ctx.moveTo(0, 0);
// Define the endpoint:
ctx.lineTo(200, 100);
// Drawing:
ctx.stroke();

Try It Yourself

Canvas Line Drawing

Line drawing uses the path in the canvas:

method description draw
beginPath() start a path. no
moveTo() move to a point. no
lineTo() draw a line to another point. no
stroke() drawing. is

method

The beginPath() method starts a new path. It does not draw anything, it just defines a new path.

The moveTo() method defines the starting point of the line. It does not draw anything, it just sets a starting point.

The lineTo() method defines the end point of the line. It does not draw anything, it just sets an endpoint.

The stroke() method actually draws the line. The default stroke color is black.

lineWidth property

The lineWidth property defines the line width to be used when drawing on the canvas.

It must be set before calling the stroke() method.

Your browser does not support the HTML5 canvas tag.

instance

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.stroke();

Try It Yourself

strokeStyle property

The strokeStyle property defines the style to be used when drawing on the canvas.

It must be set before calling the stroke() method.

Your browser does not support the HTML5 canvas tag.

instance

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.strokeStyle = "red";
ctx.stroke();

Try It Yourself

lineCap property

The lineCap property defines the style of the line's end (butt, round, or square).

The default is square (square).

It must be set before calling the stroke() method.

Your browser does not support the HTML5 canvas tag.

instance

ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(175,75);
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.stroke();

Try It Yourself

See Also:

Complete Canvas Reference Manual of CodeW3C.com