Skip to content

Instantly share code, notes, and snippets.

@dcgauld
Created April 12, 2020 13:09
Show Gist options
  • Save dcgauld/49543eeb045cfaf97caa0186f6eef033 to your computer and use it in GitHub Desktop.
Save dcgauld/49543eeb045cfaf97caa0186f6eef033 to your computer and use it in GitHub Desktop.
Pixelates an image by a given amount using canvas.
const pixelate = (image, amount = 0.1) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
canvas.style.imageRendering = 'pixelated';
context.imageSmoothingEnabled = false;
const scaledWidth = canvas.width * amount;
const scaledHeight = canvas.height * amount;
context.drawImage(image, 0, 0, scaledWidth, scaledHeight);
context.drawImage(canvas, 0, 0, scaledWidth, scaledHeight, 0, 0, canvas.width, canvas.height);
return canvas;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment