Categories
JavaScript Answers

How to Draw Lines in the HTML Canvas Without the Last Ones Being Faded?

Spread the love

Sometimes, we want to draw lines in the HTML canvas without the last ones being faded

In this article, we’ll look at how to draw lines in the HTML canvas without the last ones being faded.

Draw Lines in the HTML Canvas Without the Last Ones Being Faded

To draw lines in the HTML canvas without the last ones being faded, we can use the lineTo method and set the strokeStyle to the values we want.

For instance, we can create a canvas with:

<canvas id="myCanvas" width="400" height="400"></canvas>

Then we write:

const objCanvas = document.getElementById("myCanvas");
const objContext = objCanvas.getContext("2d");
const intGridWidth = 20;

const drawBackground = () => {
  objContext.clearRect(0, 0, objCanvas.width, objCanvas.height);
  objContext.fillStyle = 'black';
  objContext.fillRect(0, 0, objCanvas.width, objCanvas.height);
  objContext.strokeStyle = "white";
  for (let i = 1; i < objCanvas.width / intGridWidth; i++) {
    const x = Math.floor(i * intGridWidth) + 0.5;
    objContext.moveTo(x, 0);
    objContext.lineTo(x, objCanvas.height);
    objContext.stroke();
  }

  for (let i = 1; i < objCanvas.height / intGridWidth; i++) {
    const y = Math.floor(i * intGridWidth) + 0.5
    objContext.moveTo(0, y);
    objContext.lineTo(objCanvas.width, y);
    objContext.stroke();
  }

}
drawBackground();

to create the drawBackground function that clears the rectangle with:

objContext.clearRect(0, 0, objCanvas.width, objCanvas.height);

Then we set the background to black with:

objContext.fillStyle = 'black';

Then we apply the background styles with:

objContext.fillRect(0, 0, objCanvas.width, objCanvas.height);

Next, we set the line stroke style with:

objContext.strokeStyle = "white";

Next, we create the vertical grid lines with:

for (let i = 1; i < objCanvas.width / intGridWidth; i++) {
  const x = Math.floor(i * intGridWidth) + 0.5;
  objContext.moveTo(x, 0);
  objContext.lineTo(x, objCanvas.height);
  objContext.stroke();
}

We create the horizontal grid lines with:

for (let i = 1; i < objCanvas.height / intGridWidth; i++) {
  const y = Math.floor(i * intGridWidth) + 0.5
  objContext.moveTo(0, y);
  objContext.lineTo(objCanvas.width, y);
  objContext.stroke();
}

We use moveTo to move to the position we want to start drawing.

lineTo adds the line from the start and end position respectively.

stroke draws the line onto the canvas.

Conclusion

To draw lines in the HTML canvas without the last ones being faded, we can use the lineTo method and set the strokeStyle to the values we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *