Categories
JavaScript Answers

How to Stretch Images with no Antialiasing with JavaScript?

Sometimes, we want to stretch images with no antialiasing with JavaScript.

In this article, we’ll look at how to stretch images with no antialiasing with JavaScript.

Stretch Images with no Antialiasing with JavaScript

To stretch images with no antialiasing with JavaScript, we can load the image into the canvas.

Then we can copy the image pixel by pixel onto another canvas which is displayed on the screen.

For instance, we can write:

<canvas id='canvas'></canvas>

to add the canvas to display.

Then we write:

const img = new Image();
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3/OAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANCSURBVEiJtZZPbBtFFMZ/M7ubXdtdb1xSFyeilBapySVU8h8OoFaooFSqiihIVIpQBKci6KEg9Q6H9kovIHoCIVQJJCKE1ENFjnAgcaSGC6rEnxBwA04Tx43t2FnvDAfjkNibxgHxnWb2e/u992bee7tCa00YFsffekFY+nUzFtjW0LrvjRXrCDIAaPLlW0nHL0SsZtVoaF98mLrx3pdhOqLtYPHChahZcYYO7KvPFxvRl5XPp1sN3adWiD1ZAqD6XYK1b/dvE5IWryTt2udLFedwc1+9kLp+vbbpoDh+6TklxBeAi9TL0taeWpdmZzQDry0AcO+jQ12RyohqqoYoo8RDwJrU+qXkjWtfi8Xxt58BdQuwQs9qC/afLwCw8tnQbqYAPsgxE1S6F3EAIXux2oQFKm0ihMsOF71dHYx+f3NND68ghCu1YIoePPQN1pGRABkJ6Bus96CutRZMydTl+TvuiRW1m3n0eDl0vRPcEysqdXn+jsQPsrHMquGeXEaY4Yk4wxWcY5V/9scqOMOVUFthatyTy8QyqwZ+kDURKoMWxNKr2EeqVKcTNOajqKoBgOE28U4tdQl5p5bwCw7BWquaZSzAPlwjlithJtp3pTImSqQRrb2Z8PHGigD4RZuNX6JYj6wj7O4TFLbCO/Mn/m8R+h6rYSUb3ekokRY6f/YukArN979jcW+V/S8g0eT/N3VN3kTqWbQ428m9/8k0P/1aIhF36PccEl6EhOcAUCrXKZXXWS3XKd2vc/TRBG9O5ELC17MmWubD2nKhUKZa26Ba2+D3P+4/MNCFwg59oWVeYhkzgN/JDR8deKBoD7Y+ljEjGZ0sosXVTvbc6RHirr2reNy1OXd6pJsQ+gqjk8VWFYmHrwBzW/n+uMPFiRwHB2I7ih8ciHFxIkd/3Omk5tCDV1t+2nNu5sxxpDFNx+huNhVT3/zMDz8usXC3ddaHBj1GHj/As08fwTS7Kt1HBTmyN29vdwAw+/wbwLVOJ3uAD1wi/dUH7Qei66PfyuRj4Ik9is+hglfbkbfR3cnZm7chlUWLdwmprtCohX4HUtlOcQjLYCu+fzGJH2QRKvP3UNz8bWk1qMxjGTOMThZ3kvgLI5AzFfo379UAAAAASUVORK5CYII=";
img.onload = () => {
  const scale = 8;
  const srcCanvas = document.createElement('canvas');
  srcCanvas.width = img.width;
  srcCanvas.height = img.height;

  const srcCtx = srcCanvas.getContext('2d');
  srcCtx.drawImage(img, 0, 0);
  const srcData = srcCtx.getImageData(0, 0, img.width, img.height).data;

  const dstCanvas = document.getElementById('canvas');
  dstCanvas.width = img.width * scale;
  dstCanvas.height = img.height * scale;
  const dstCtx = dstCanvas.getContext('2d');

  let offset = 0;
  for (let y = 0; y < img.height; ++y) {
    for (let x = 0; x < img.width; ++x) {
      const r = srcData[offset++];
      const g = srcData[offset++];
      const b = srcData[offset++];
      const a = srcData[offset++] / 100.0;
      dstCtx.fillStyle = 'rgba(' + [r, g, b, a].join(',') + ')';
      dstCtx.fillRect(x * scale, y * scale, scale, scale);
    }
  }
};

to create an img element with the Image constructor.

Then we set the src property of the image to load the image with the given URL.

Next, we set the img.onload property to a function that creates the canvas.

We set the width and height of the canvas to the width and height of the image with:

srcCanvas.width = img.width;
srcCanvas.height = img.height;

Then we draw the image onto the canvas with:

const srcCtx = srcCanvas.getContext('2d');
srcCtx.drawImage(img, 0, 0);
const srcData = srcCtx.getImageData(0, 0, img.width, img.height).data;

Next, we get the destination canvas element which we created with:

const dstCanvas = document.getElementById('canvas');

And we set the width and height of the destination canvas with:

dstCanvas.width = img.width * scale;
dstCanvas.height = img.height * scale;

And finally, we copy each pixel from the source canvas to the destination canvas with:

let offset = 0;
for (let y = 0; y < img.height; ++y) {
  for (let x = 0; x < img.width; ++x) {
    const r = srcData[offset++];
    const g = srcData[offset++];
    const b = srcData[offset++];
    const a = srcData[offset++] / 100.0;
    dstCtx.fillStyle = 'rgba(' + [r, g, b, a].join(',') + ')';
    dstCtx.fillRect(x * scale, y * scale, scale, scale);
  }
}

Now we can see the pixelated version of the original image when we run the code.

Conclusion

To stretch images with no antialiasing with JavaScript, we can load the image into the canvas.

Then we can copy the image pixel by pixel onto another canvas which is displayed on the screen.

Categories
JavaScript Answers

How to See the Result of readAsText() with HTML5 JavaScript File API?

Sometimes, we want to see the result of readAsText() with HTML5 JavaScript File API.

In this article, we’ll look at how to see the result of readAsText() with HTML5 JavaScript File API.

See the Result of readAsText() with HTML5 JavaScript File API

To see the result of readAsText() with HTML5 JavaScript File API, we can get the data from the onload callback.

For instance, we write:

<input type='file'>

to add a file input.

Then we write:

const fr = new FileReader();
fr.onload = (e) => {
  console.log(e.target.result)
};

const input = document.querySelector('input')
input.addEventListener('change', (e) => {
  const [file] = e.target.files
  fr.readAsText(file);
})

to create a FileReader instance and assign it to fr.

Then we set the fr.onload property to a function that gets the text with e.target.result and log it with console.log.

Next, we select the input with document.querySelector.

Then we call input.addEventListener with 'change' to add a change event listener.

The change event is emitted when we select a file.

In the event handler callback, we get the selected files with e.target.files.

Then we call fr.readAsText with file to read the file‘s content as text.

Therefore, when we select a text file with the file input, we see the text display in the console.

Conclusion

To see the result of readAsText() with HTML5 JavaScript File API, we can get the data from the onload callback.

Categories
JavaScript Answers

How to Check if a Path is Absolute or Relative with Node.js?

Sometimes, we want to check if a path is absolute or relative with Node.js.

In this article, we’ll look at how to check if a path is absolute or relative with Node.js.

Check if a Path is Absolute or Relative with Node.js

To check if a path is absolute or relative with Node.js, we can use the isAbsolute method from the path module.

For instance, we can write:

const path = require('path');
const myPath = '/foo/bar'
if (path.isAbsolute(myPath)) {
  console.log('absolute path')
}

to check if myPath is an absolute path with path.isAbsolute.

It should return true since it’s an absolute path.

And therefore, the console log should run.

Conclusion

To check if a path is absolute or relative with Node.js, we can use the isAbsolute method from the path module.

Categories
JavaScript Answers

How to Add a Close Button in div to Close the div with JavaScript?

Sometimes, we want to add a close button in div to close the div with JavaScript.

In this article, we’ll look at how to add a close button in div to close the div with JavaScript.

Add a Close Button in div to Close the div with JavaScript

To add a close button in div to close the div with JavaScript, we can add a click listener to the close button.

For instance, we can write:

<div>
  <button id='close'>
    close
  </button>
  <h3>title</h3>
  <p class="text">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  </p>
</div>

to add a close button in a div.

Then we write:

window.onload = () => {
  document.getElementById('close').onclick = function() {
    this.parentNode.remove()
    return false;
  };
};

We set the window.onload property to a function that runs when the DOM is loaded.

In the function, we select the close button with document.getElementById('close').

And we set the onclick property to a function that removes the the parent of the close button, which is the div.

We get the parent of the close button with this.parentNode.

Then we call remove on it to remove the parent node which is the div.

And we return false to prevent the default action.

Now when we click the close button, the div is removed from the screen.

Conclusion

To add a close button in div to close the div with JavaScript, we can add a click listener to the close button.

Categories
JavaScript Answers

How to Run JavaScript Code When we Click on a Link?

Sometimes, we want to run JavaScript code when we click on a link.

In this article, we’ll look at how to run JavaScript code when we click on a link.

Run JavaScript Code When we Click on a Link

To run JavaScript code when we click on a link, we can attach a click event listener to the a element.

For instance, we can write:

<a href="#">LinkText</a>

to add an a tag.

We set href to # to avoid going to any URL when we click on the link.

Then we write:

const a = document.querySelector('a')
a.addEventListener('click', () => {
  console.log('clicked')
})

to get the a element with document.querySelector.

Then we call addEventListener with 'click' to add a click listener.

The 2nd argument is a callback that runs when we click on the link.

Therefore, we should see 'clicked' logged when we click on the link.

Conclusion

To run JavaScript code when we click on a link, we can attach a click event listener to the a element.