Categories
JavaScript Answers

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

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.

Categories
JavaScript Answers

How to Convert a File Input Value to a Byte Array with JavaScript?

Sometimes, we want to convert a file input value to a byte array with JavaScript.

In this article, we’ll look at how to convert a file input value to a byte array with JavaScript.

Convert a File Input Value to a Byte Array with JavaScript

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

For instance, if we have the following HTML:

<input type='file'>

Then we can write:

const input = document.querySelector('input')
const reader = new FileReader();
const fileByteArray = [];

input.addEventListener('change', (e) => {
  reader.readAsArrayBuffer(e.target.files[0]);
  reader.onloadend = (evt) => {
    if (evt.target.readyState === FileReader.DONE) {
      const arrayBuffer = evt.target.result,
        array = new Uint8Array(arrayBuffer);
      for (const a of array) {
        fileByteArray.push(a);
      }
      console.log(fileByteArray)
    }
  }
})

to get the input with document.querySelector .

Then we create a FileReader instance with:

const reader = new FileReader();

And we create a byte array with:

const fileByteArray = [];

Next, we call reader.readAsArrayBuffer in the file input’s change event listener to read the file into an array buffer.

Then we set the onloadend function to a function that runs when the file is loaded.

In the function, we get the buffer result with assign it to arrayBuffer .

Then we create the Uint8Array and assign it to array .

Finally, we push all the array entries into the fileByteArray .

Conclusion

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

Categories
JavaScript Answers

How to Get the Number of Lines in a textarea Using JavaScript?

Sometimes, we want to get the number of lines in a textarea using JavaScript.

In this article, we’ll look at how to get the number of lines in a textarea using JavaScript.

Get the Number of Lines in a textarea Using JavaScript

To get the number of lines in a textarea using JavaScript, we can call split on the input value of the textarea by the newline character.

Then we get the length of the returned string array.

For instance, we can write:

<textarea></textarea>

to create a textarea element.

Then we write:

const textarea = document.querySelector('textarea')
textarea.addEventListener('input', () => {
  const text = textarea.value;
  const lines = text.split("\n");
  const count = lines.length;
  console.log(count);
})

We select the textarea with the document.querySelector.

Then we call addEventListener to listen to the input event.

In the input event handler, we get the textarea’s input value with textarea.value.

Then we call split with \n to split the value by the newline character.

And finally, we get the length of the split lines.

Therefore, now we should see the number of lines logged as we type.

Conclusion

To get the number of lines in a textarea using JavaScript, we can call split on the input value of the textarea by the newline character.

Then we get the length of the returned string array.

Categories
JavaScript Answers

How to Calculate the UTC Offset Given a Time Zone String in JavaScript?

Sometimes, we want to calculate the UTC offset given a time zone string in JavaScript.

In this article, we’ll look at how to calculate the UTC offset given a time zone string in JavaScript.

Calculate the UTC Offset Given a Time Zone String in JavaScript

To calculate the UTC offset given a time zone string in JavaScript, we can use the JavaScript date’s toLocaleString method to get the time zone offset.

For instance, we can weite:

const getTimezoneOffset = (d, timeZone) => {
  const a = d.toLocaleString("ja", {
    timeZone
  }).split(/[/s:]/);
  a[1]--;
  const t1 = Date.UTC(...a);
  const t2 = new Date(d).setMilliseconds(0);
  return (t2 - t1) / 60 / 1000;
}

console.log(getTimezoneOffset(new Date(2016, 0, 1), "America/New_York"))

to create the getTimezoneOffset function that takes the d date and timeZone .

We get the date parts in an array with the toLocaleString method which we called with the timeZone .

Then we subtract the month number by 1 to match the JavaScript convention with:

a[1]--;

Next, we call Date.UTC with the a array spread as the arguments to create t1

Then we create t2 with 0 milliseconds.

Next, we subtract t2 and t1 and divide that by 60 seconds and return that.

Now we get the time zone offset in minutes.

Conclusion

To calculate the UTC offset given a time zone string in JavaScript, we can use the JavaScript date’s toLocaleString method to get the time zone offset.

Categories
JavaScript Answers

How to Draw a Circle in HTML5 Canvas Using JavaScript?

Sometimes, we want to draw a circle in HTML5 canvas using JavaScript.

In this article, we’ll look at how to draw a circle in HTML5 canvas using JavaScript.

Draw a Circle in HTML5 Canvas Using JavaScript

To draw a circle in HTML5 canvas using JavaScript, we can use the arc method.

For instance, we can add the canvas element by writing:

<canvas style='width: 300px; height: 300px'></canvas>

Then we write:

const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();

We select the canvas with document.querySelector.

Then we get the canvas context with getContext.

Next, we set the center’s coordinates with centerX and centerY.

We then we set the radius of the circle.

Next, we call beginPath to start drawing.

Then we call arc with centerX, centerY, radius, 0, 2 * Math.PI and `false.

We need 2 * Math.PI to draw an arc forms the circle.

Next, we set the fillStyle to set the fill of the circle.

Then we call fill to draw the fill.

Next, we set lineWidth to set the outline’s width.

Then we set strokeStyle to set the outline color.

And finally, we call stroke to draw the outline.

Now we see a circle with green fill color and black outline drawn.

Conclusion

To draw a circle in HTML5 canvas using JavaScript, we can use the arc method.