HTML Canvas Lines
Canvas Line Drawing
To draw a line in canvas, we use the following methods:
Method | Description | Draws |
---|---|---|
beginPath() |
Declares that we are about to draw a new path (without drawing) | No |
moveTo(x,y) |
Sets the start-point of the line in the canvas (without drawing) | No |
lineTo(x,y) |
Sets the end-point of the line in the canvas (without drawing) | No |
stroke() |
Draws the line. The default stroke color is black | Yes |
Example
Define a start-point in position (0,0), and an end-point in position (200,100). Then use
stroke()
to actually draw the line:
<script>
// Create a Canvas:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Define a new path
ctx.beginPath();
// Set a start-point
ctx.moveTo(0, 0);
// Set an end-point
ctx.lineTo(200, 100);
// Stroke it (Do the Drawing)
ctx.stroke();
</script>
Try it Yourself »
The lineWidth Property
The lineWidth
property defines the width of
the line.
It must be set before calling the stroke()
method.
Example
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.stroke();
</script>
Try it Yourself »
The strokeStyle Property
The strokeStyle
property defines the color
of the line.
It must be set before calling the stroke()
method.
Example
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.strokeStyle = "red";
ctx.stroke();
</script>
Try it Yourself »
The lineCap Property
The lineCap
property defines the cap style
of the line ("butt", "round" or "square").
The default is "butt".
It must be set before calling the stroke()
method.
Example
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(175,75);
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.stroke();
</script>
Try it Yourself »