Skip to content

Instantly share code, notes, and snippets.

@40
Created March 24, 2012 04:31
Show Gist options
  • Save 40/2178291 to your computer and use it in GitHub Desktop.
Save 40/2178291 to your computer and use it in GitHub Desktop.
:Pixelate Image in HTML5 Canvas
function focusImage(canvas, context, imageObj, pixelation){
var sourceWidth = imageObj.width;
var sourceHeight = imageObj.height;
var sourceX = canvas.width / 2 - sourceWidth / 2;
var sourceY = canvas.height / 2 - sourceHeight / 2;
var destX = sourceX;
var destY = sourceY;
var imageData = context.getImageData(sourceX, sourceY,
sourceWidth, sourceHeight);
var data = imageData.data;
for (var y = 0; y < sourceHeight; y += pixelation) {
for (var x = 0; x < sourceWidth; x += pixelation) {
// get the color components of the sample pixel
var red = data[((sourceWidth * y) + x) * 4];
var green = data[((sourceWidth * y) + x) * 4 + 1];
var blue = data[((sourceWidth * y) + x) * 4 + 2];
// overwrite pixels in a square below and to
// the right of the sample pixel, whos width and
// height are equal to the pixelation amount
for (var n = 0; n < pixelation; n++) {
for (var m = 0; m < pixelation; m++) {
if (x + m < sourceWidth) {
data[((sourceWidth * (y + n)) + (x + m)) *
4] = red;
data[((sourceWidth * (y + n)) + (x + m)) *
4 + 1] = green;
data[((sourceWidth * (y + n)) + (x + m)) *
4 + 2] = blue;
}
}
}
}
}
// overwrite original image
context.putImageData(imageData, destX, destY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment