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 Lines


Example

Your browser does not support the HTML5 canvas tag.
// Create a Canvas:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Define a new Path:
ctx.beginPath();

// Define a start Point
ctx.moveTo(0, 0);

// Define an end Point
ctx.lineTo(200, 100);

// Stroke it (Do the Drawing)
ctx.stroke();
Try it Yourself »

Canvas Line Drawing

Line drawing uses Paths in the Canvas:

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.



The lineWidth Property

The lineWidth property defines the line width 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();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.stroke();
Try it Yourself »

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();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.strokeStyle = "red";
ctx.stroke();
Try it Yourself »

The lineCap Property

The lineCap property defines the cap style of the line (butt, round or square).

The default is square.

It must be set before calling the stroke() method.

Example

Your browser does not support the HTML5 canvas tag.
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(175,75);
ctx.lineWidth = 10;
ctx.lineCap = "round";
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.