HTML Canvas Lines
Example
// 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:
Method | Description | Draws |
---|---|---|
beginPath() | Start a path | No |
moveTo() | Move to a point | No |
lineTo() | Line to another point | No |
stroke() | Do the drawing | Yes |
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
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
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
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(175,75);
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.stroke();
Try it Yourself »