How to pixelate an image with canvas and javascript

You don’t need to iterate pixel buffer to create a pixelating effect.

Simply turn off image smoothing and enlarge a small version of the image to the canvas. This will also mean you can use any image as source (CORS-wise).

Example:

Fiddle demo

// get a block size (see demo for this approach)
var size = blocks.value / 100,
    w = canvas.width * size,
    h = canvas.height * size;

// draw the original image at a fraction of the final size
ctx.drawImage(img, 0, 0, w, h);

// turn off image aliasing
ctx.msImageSmoothingEnabled = false;
ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;

// enlarge the minimized image to full size    
ctx.drawImage(canvas, 0, 0, w, h, 0, 0, canvas.width, canvas.height);

In the demo you can animate this effect to see that the performance is very good compared to an pixel iterating method as the browser takes care of the “pixelation” internally in compiled code.

Leave a Comment