Created
March 8, 2014 20:38
-
-
Save coleww/9438486 to your computer and use it in GitHub Desktop.
pixel array wrapper for haxing the canvas pixels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//dealing with the pixel data from the canvas is a pain | |
//gotta multiply everything by four everywhere all the time | |
//made an object to wrap up all that badness | |
//a "pixel" is a 4 element array. 0 => R, 1 => G, 2 => B, 3 => A | |
var PixelArray = root.PixelArray = function(ctx, w, h){ | |
this._pixels = ctx.getImageData(0, 0, w, h).data; | |
this.w = w; | |
this.h = h; | |
this.numPixels = this._pixels.length / 4; | |
}; | |
PixelArray.prototype.getPixel = function(x, y){ | |
if(x > this.w || y > this.h || x < 0 || y < 0) { | |
throw "OUTTA BOUNDS!"; | |
} | |
var pixelPosition = (y * this.w + x) * 4; | |
return this._pixels.slice(pixelPosition, pixelPosition + 4); | |
}; | |
PixelArray.prototype.getColor = function(pixel, alpha){ | |
if(alpha !== undefined){ | |
pixel[3] = alpha; | |
}//is this a horrible thing to do? maybe... maybe... | |
return "rgba(" + pixel.join(",") + ")"; | |
}; | |
//oh and you also have to run this hack first to make this work because i guess pixel arrays are oh so super special | |
if (typeof Uint8ClampedArray !== 'undefined') { | |
Uint8ClampedArray.prototype.slice = Array.prototype.slice; //Firefox and Chrome | |
} else if(typeof CanvasPixelArray!== 'undefined') { | |
CanvasPixelArray.prototype.slice = Array.prototype.slice; //IE10 and IE9 | |
} else { | |
// Deprecated browser | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment