HTML Canvas Shapes
Example
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(100,20);
ctx.lineTo(175,100);
ctx.lineTo(20,100);
ctx.lineTo(20,20);
ctx.stroke();
Try it Yourself »
Canvas Line Drawing
Line drawing in Canvas uses Paths:
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.
More Examples
Example
ctx.beginPath();
ctx.moveTo(100,20);
ctx.lineTo(175,100);
ctx.lineTo(20,100);
ctx.lineTo(100,20);
ctx.stroke();
Try it Yourself »
Example
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(175,20);
ctx.lineTo(175,100);
ctx.lineTo(20,100);
ctx.lineTo(20,20);
ctx.stroke();
Try it Yourself »
Note
You do not have to draw 4 lines to draw a rectangle.
In the next chapter you will learn to use the drawRect() method.
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();
// Define a rectangle
ctx.moveTo(20,20);
ctx.lineTo(175,20);
ctx.lineTo(175,100);
ctx.lineTo(20,100);
ctx.lineTo(20,20);
// Define a triangle
ctx.moveTo(100,20);
ctx.lineTo(175,100);
ctx.lineTo(20,100);
ctx.lineTo(100,20);
ctx.strokeStyle = "red";
ctx.stroke();
Try it Yourself »