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).
First, an in-memory HTML <canvas> with a 2D rendering context having the same size as the original image to be pixelated is initialized. Next, the original image is drawn into the canvas with the drawImage() function. This is required to call the getImageData() function, which allows you to retrieve the list of pixels.
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.
Just keep in mind, there is a few javascript libraries doing same effect, for example pixelate or close-pixelate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With