How to Draw a Line in JavaScript (original) (raw)

Summary: in this tutorial, you’ll learn how to draw a line using the Canvas API.

Steps for drawing a line in JavaScript

To draw a line on a canvas, you use the following steps:

Set the line stroke

If you want to stroke the line with the strokeStyle, you can call the stroke() method after calling the lineTo(x,y) method.

Set the line width

To set the width for a line, you use the lineWidth property of the 2D drawing context before calling stroke() method:

ctx.lineWidth = 10;

The lineTo(x,y) method

The lineTo(x,y ) method accepts both positive and negative arguments.

If the x is positive, the lineTo(x,y) method draws the line from the starting point to the right. Otherwise, it draws the line from the starting point to the left.

If the y is positive, the lineTo(x,y) method draws the line from the starting point down the y-axis. Otherwise, it draws the line from the starting point up to the y-axis.

Drawing a line example

The following shows the index.html file that contains a canvas element:

`

JavaScript - Drawing a Line
<h1>JavaScript - Drawing a Line</h1>

<canvas id="canvas" height="400" width="500">
</canvas>
<script src="js/app.js"></script>
`Code language: HTML, XML (xml)

And this app.js contains that draws a line with the color red, 5-pixel width from the point (100, 100) to (300, 100):

`function draw() { const canvas = document.querySelector('#canvas');

if (!canvas.getContext) {
    return;
}
const ctx = canvas.getContext('2d');

// set line stroke and line width
ctx.strokeStyle = 'red';
ctx.lineWidth = 5;

// draw a red line
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(300, 100);
ctx.stroke();

} draw();`Code language: JavaScript (javascript)

The following shows the output:

Here is the link that shows the canvas with the line.

Develop a resuable drawLine() function

The following drawLine() function draws a line from one point to another with a specified stroke and width:

`function drawLine(ctx, begin, end, stroke = 'black', width = 1) { if (stroke) { ctx.strokeStyle = stroke; }

if (width) {
    ctx.lineWidth = width;
}

ctx.beginPath();
ctx.moveTo(...begin);
ctx.lineTo(...end);
ctx.stroke();

} `Code language: JavaScript (javascript)

To draw a line from (100,100) to (100,300) with the line color green and line width 5 pixels, you can call the drawLine() function as follows:

const canvas = document.querySelector('#canvas'); if (canvas.getContext) { const ctx = canvas.getContext('2d'); drawLine(ctx, [100, 100], [100, 300], 'green', 5); } Code language: JavaScript (javascript)

Summary

Was this tutorial helpful ?