Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
     ❯   

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 »

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2023 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.