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 AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

HTML Canvas Lines


Canvas Line Drawing

To draw a line in canvas, we use the following methods:

Method Description Draws
beginPath() Declares that we are about to draw a new path (without drawing) No
moveTo(x,y) Sets the start-point of the line in the canvas (without drawing) No
lineTo(x,y) Sets the end-point of the line in the canvas (without drawing) No
stroke() Draws the line. The default stroke color is black Yes

Example

Sorry, your browser does not support canvas.

Define a start-point in position (0,0), and an end-point in position (200,100). Then use stroke() to actually draw the line:

<script>
// Create a Canvas:
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Define a new path
ctx.beginPath();

// Set a start-point
ctx.moveTo(0, 0);

// Set an end-point
ctx.lineTo(200, 100);

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


The lineWidth Property

The lineWidth property defines the width of the line.

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

Example

Sorry, your browser does not support canvas.
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.stroke();
</script>
Try it Yourself »

The strokeStyle Property

The strokeStyle property defines the color of the line.

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

Example

Sorry, your browser does not support canvas.
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.lineWidth = 10;
ctx.strokeStyle = "red";
ctx.stroke();
</script>
Try it Yourself »

The lineCap Property

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

The default is "butt".

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

Example

Sorry, your browser does not support canvas.
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(175,75);
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.stroke();
</script>
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-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.