HTML Canvas Lines


Example

Your browser does not support the HTML5 canvas tag.
// Create a Canvas:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Define a new Path:
ctx.beginPath();

// Define a start Point
ctx.moveTo(0, 0);

// Define an end Point
ctx.lineTo(200, 100);

// Stroke it (Do the Drawing)
ctx.stroke();
Try it Yourself »

Canvas Line Drawing

Line drawing uses Paths in the Canvas:

MethodDescriptionDraws
beginPath()Start a pathNo
moveTo()Move to a pointNo
lineTo()Line to another pointNo
stroke()Do the drawingYes

The Methods

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

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

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

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



The lineWidth Property

The lineWidth property defines the line width to use, when drawing in the canvas context.

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

Example

Your browser does not support the HTML5 canvas tag.
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.stroke();
Try it Yourself »

The strokeStyle Property

The strokeStyle property defines the style to use, when drawing in the canvas context.

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

Example

Your browser does not support the HTML5 canvas tag.
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.strokeStyle = "red";
ctx.stroke();
Try it Yourself »

The lineCap Property

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

The default is square.

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

Example

Your browser does not support the HTML5 canvas tag.
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(175,75);
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.stroke();
Try it Yourself »

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.