Skip to content

Instantly share code, notes, and snippets.

@jrtashjian
Created April 30, 2022 01:55
Show Gist options
  • Save jrtashjian/323b0c2d2feb0bf764cbee86f6d8afd7 to your computer and use it in GitHub Desktop.
Save jrtashjian/323b0c2d2feb0bf764cbee86f6d8afd7 to your computer and use it in GitHub Desktop.
Pixelated images in JS with Canvas
function pixelate( event ) {
// Set pixel size.
const pixelSize = 16;
// Get original image dimensions.
const element = event.target;
const originalImageWidth = parseInt( element.getAttribute( 'width' ) );
const originalImageHeight = parseInt( element.getAttribute( 'height' ) );
// Create a canvas for rendering pixelated image.
const canvas = document.createElement( 'canvas' );
canvas.style.width = '100%';
canvas.width = originalImageWidth;
canvas.height = originalImageHeight;
var ctx = canvas.getContext( '2d' );
ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
// Insert the canvas to the page.
element.style.display = 'none';
element.parentNode.insertBefore( canvas, element );
const drawOriginalImage = () => {
ctx.drawImage( element, 0, 0, originalImageWidth, originalImageHeight );
};
const drawPixelatedImage = () => {
// Pixelate the image.
const width = ( originalImageWidth / pixelSize );
const height = ( originalImageHeight / pixelSize );
ctx.drawImage( element, 0, 0, width, height );
ctx.drawImage( canvas, 0, 0, width, height, 0, 0, canvas.width, canvas.height );
};
// Reveal original resolution on hover.
canvas.addEventListener( 'mouseenter', drawOriginalImage );
canvas.addEventListener( 'mouseleave', drawPixelatedImage );
drawPixelatedImage();
}
document.addEventListener( 'DOMContentLoaded', () => {
document.querySelectorAll( 'img' ).forEach( ( image ) => {
image.addEventListener( 'load', ( event ) => pixelate( event ) );
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment