Categories
JavaScript Answers

How to pixelate an image with canvas and JavaScript?

Spread the love

Sometimes, we want to pixelate an image with canvas and JavaScript.

In this article, we’ll look at how to pixelate an image with canvas and JavaScript.

How to pixelate an image with canvas and JavaScript?

To pixelate an image with canvas and JavaScript, we can call drawImage with a size smaller than the canvas size.

For instance, we write:

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

to add a canvas.

Then we write:

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
const img = new Image()
img.onload = () => {
  const size = 0.1,
    w = canvas.width * size,
    h = canvas.height * size;

  ctx.drawImage(img, 0, 0, w, h);

  ctx.msImageSmoothingEnabled = false;
  ctx.mozImageSmoothingEnabled = false;
  ctx.webkitImageSmoothingEnabled = false;
  ctx.imageSmoothingEnabled = false;

  ctx.drawImage(canvas, 0, 0, w, h, 0, 0, canvas.width, canvas.height);
}
img.src = 'https://picsum.photos/200/300'

We select the canvas with document.querySelector.

Then we get the context with getContext.

Next, we create a new Image instance and set the onload property to a function that calls drawImage with width w and height h that is smaller than the canvas size.

We then set image smoothing settings all to false.

Finally, we call drawImage with width w and height h again to draw the image.

Now we should see a pixelated image drawn.

Conclusion

To pixelate an image with canvas and JavaScript, we can call drawImage with a size smaller than the canvas size.

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 *