Setting Line Width

Change the width of a line on the canvas

The lineWidth property of the context ctx sets the width of lines drawn in the future. This value is set before drawing shapes like lines or circles.

const canvas = document.querySelector(‘#myCanvas’);

const ctx = canvas.getContext(‘2d’);

ctx.beginPath();

ctx.moveTo(-35,-7);

ctx.lineTo(300,100);

ctx.lineWidth = 14;

ctx.stroke();

The code ctx.lineWidth = 14; sets the width of the lines drawn on a canvas using the HTML Canvas 2D Context (ctx) to 14 pixels. This property affects all strokes drawn after this setting is applied and until it is changed to a different value. When you draw shapes, lines, or paths on the canvas, the lineWidth property determines how thick or thin the line appears.

For example, if you use ctx.stroke(); to outline a shape or to draw a line, the thickness of that line will be 14 pixels as specified by ctx.lineWidth = 14;.

Here’s a brief example demonstrating its effect:

// Assuming ctx is already defined as the 2D context of a canvas

ctx.lineWidth = 14; // Sets the line width to 14 pixels

// Begin a new path

ctx.beginPath();

// Move the starting point of the line

ctx.moveTo(50, 50);

// Define the ending point of the line

ctx.lineTo(200, 50);

// Stroke the path with the current line width and stroke style

ctx.stroke();

In this example, a line will be drawn from the coordinates (50, 50) to (200, 50) with a thickness of 14 pixels. The appearance of the stroke, other than its width, such as its color, can be customized using other properties like ctx.strokeStyle