Tuesday, 1 October 2013

How to pixelate an image with canvas and javascript

How to pixelate an image with canvas and javascript

I've been experimenting a bit with the canvas element and was curious how
to pull off an effect. I've somewhat got what I'm looking for from a
collection of tutorials and demos, but I need some assistance getting the
rest of the way there. What I'm looking for is to pixelate an image on
mouseover, then refocus/un-pixelate it on mouseout. You can see a good
example of the effect at http://www.cropp.com/ when mousing over the
blocks that are below the main carousel.
Here is a link to a fiddle I started. The fiddle won't work because you
can't use cross domain images (womp womp), but you can still see my code
thus far. When mousing over my canvas object I'm able to pixelate the
image, but it's kind of backwards to what I'm attempting to get. Any help
or advice would be greatly appreciated.
var pixelation = 40,
fps = 120,
timeInterval = 1000 / fps,
canvas = document.getElementById('photo'),
context = canvas.getContext('2d'),
imgObj = new Image();
imgObj.src = 'images/me.jpg';
imgObj.onload = function () {
context.drawImage(imgObj, 0, 0);
};
canvas.addEventListener('mouseover', function() {
var interval = setInterval(function () {
context.drawImage(imgObj, 0, 0);
if (pixelation < 1) {
clearInterval(interval);
pixelation = 40;
} else {
pixelate(context, canvas.width, canvas.height, 0, 0);
}
}, timeInterval);
});
function pixelate(context, srcWidth, srcHeight, xPos, yPos) {
var sourceX = xPos,
sourceY = yPos,
imageData = context.getImageData(sourceX, sourceY, srcWidth,
srcHeight),
data = imageData.data;
for (var y = 0; y < srcHeight; y += pixelation) {
for (var x = 0; x < srcWidth; x += pixelation) {
var red = data[((srcWidth * y) + x) * 4],
green = data[((srcWidth * y) + x) * 4 + 1],
blue = data[((srcWidth * y) + x) * 4 + 2];
for (var n = 0; n < pixelation; n++) {
for (var m = 0; m < pixelation; m++) {
if (x + m < srcWidth) {
data[((srcWidth * (y + n)) + (x + m)) * 4] = red;
data[((srcWidth * (y + n)) + (x + m)) * 4 + 1] =
green;
data[((srcWidth * (y + n)) + (x + m)) * 4 + 2] =
blue;
}
}
}
}
}
// overwrite original image
context.putImageData(imageData, xPos, yPos);
pixelation -= 1;
}

No comments:

Post a Comment