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 Stringify an ES6 Class Property with Getter or Setter into JSON?

Sometimes, we want to stringify an ES6class property with getter or setter into JSON.

In this article, we’ll look at how to stringify an ES6class property with getter or setter into JSON.

Stringify an ES6 Class Property with Getter or Setter into JSON

To stringify an ES6class property with getter or setter into JSON, we can add the toJSON method to the class to customize what to put in the JSON string.

For instance, we can write:

class MyClass {
  constructor(property) {
    this.property = property
  }

  set property(prop) {
    this._property = prop
  }

  get property() {
    return this._property
  }

  toJSON() {
    return {
      property: this.property
    }
  }
}

console.log(JSON.stringify(new MyClass('foo')))

to add the property property into the MyClass class.

We have the this.property instance property which is formed with getters and setters.

We just return an object with this.property set to the property property in toJSON to include.

Then when we create a new MyClass instance, we should see the this.property logged when we cal JSON.stringify on the MyClass instance.

Conclusion

To stringify an ES6class property with getter or setter into JSON, we can add the toJSON method to the class to customize what to put in the JSON string.

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 Change the First Letter of Each Word to Upper Case with JavaScript?

To change the first letter of each word to upper case with JavaScript, we can use the JavaScript string’s replace method with a callback to change the first letter of each word to uppercase.

For instance, we can write:

const str = "hello world";
const newStr = str.toLowerCase().replace(/b[a-z]/g, (letter) => {
  return letter.toUpperCase();
});
console.log(newStr)

We call str.toLowerCase to convert str to lower case.

Then we call replace on it with a regex to match all lowercase letters that are the first letter of a word with /b[a-z]/g .

The callback gets the matched letter and call toUpperCase on it.

Therefore, newStr is 'Hello World' .