HTML Canvas Shapes


Example

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

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.



More Examples

Example

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

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 »

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

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

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