Skip to content

Instantly share code, notes, and snippets.

@gkoberger
Created September 20, 2012 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkoberger/3753689 to your computer and use it in GitHub Desktop.
Save gkoberger/3753689 to your computer and use it in GitHub Desktop.
Get Colors From Image
// Create a new image
var image = new Image();
var imageData = false;
image.crossOrigin = '';
image.src = 'http://p.gkoberger.net/firefox/firefox.png';
// When it loads, we’re going to put it into a canvas element
image.onload = function () {
var cnvs = document.createElement('canvas');
cnvs.width = image.width;
cnvs.height = image.height;
document.getElementsByTagName('body')[0].appendChild(cnvs);
// This gives the drawing methods we need.
var ctx = cnvs.getContext('2d');
ctx.drawImage(image, 0, 0);
// Only some browsers support getImageData.
try {
imageData = ctx.getImageData(0, 0, cnvs.width, cnvs.height);
} catch (e) {
alert("Your browser doesn’t support");
return;
}
};
// Returns RGBA
function getColor(x, y) {
if (!imageData) return;
// Weird math to get the index; just trust me on this one
var index = (y * imageData.width + x) * 4,
red = imageData.data[index],
green = imageData.data[index + 1],
blue = imageData.data[index + 2],
alpha = imageData.data[index + 3];
// I’m returning RGBA, since it’s something we can use when writing HTML
return "rgba(" + red + "," + green + "," + blue + "," + alpha + ");";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment