Shapes in HTML Canvas

Instance

Your browser does not support the HTML5 canvas tag.

Example 1

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 uses paths in the canvas:

The method Description Draw
beginPath() Start a new path. No
moveTo() Move to a point. No
lineTo() Draw a line to another point. No
stroke() Drawing. Is

The method

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

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

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

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

More examples

Example 2

Your browser does not support the HTML5 canvas tag.
ctx.beginPath();
ctx.moveTo(100,20);
ctx.lineTo(175,100);
ctx.lineTo(20,100);
ctx.lineTo(100,20);
ctx.stroke();

Try It Yourself

Example 3

Your browser does not support the HTML5 canvas tag.
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

Hint

If you want to draw a rectangle, you do not need to draw 4 lines.

In the next chapter, you will learn to use drawRect() method to draw a rectangle.

strokeStyle attribute

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

Must be called stroke() Set it before the method.

Your browser does not support the HTML5 canvas tag.

Instance

ctx.beginPath();
// Define rectangle
ctx.moveTo(20,20);
ctx.lineTo(175,20);
ctx.lineTo(175,100);
ctx.lineTo(20,100);
ctx.lineTo(20,20);
// Define 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

See Also:

Complete Canvas Reference Manual of CodeW3C.com