Skip to content

Instantly share code, notes, and snippets.

@codepo8
Last active December 17, 2015 15:29
Show Gist options
  • Save codepo8/5631638 to your computer and use it in GitHub Desktop.
Save codepo8/5631638 to your computer and use it in GitHub Desktop.
Two handy helper routines for canvas work
// Get the canvas and the context
var c = document.querySelector('canvas');
var cx = c.getContext('2d');
// pixelcolour returns an object of rgba for the pixel at x and y
// great for checking if you are in a certain boundary or for
// colourpickers
function pixelcolour(x, y) {
var pixels = cx.getImageData(0, 0, c.width, c.height);
var index = ((y * (pixels.width * 4)) + (x * 4));
return {
r:pixels.data[index],
g:pixels.data[index + 1],
b:pixels.data[index + 2],
a:pixels.data[index + 3]
};
};
// getpixelamount returns the amount of pixels of a
// certain rgb colour. Handy to test how much has
// been changed or see how many could be replaced
function getpixelamount(r, g, b) {
var pixels = cx.getImageData(0, 0, c.width, c.height);
var all = pixels.data.length;
var amount = 0;
for (i = 0; i < all; i += 4) {
if (pixels.data[i] === r &&
pixels.data[i+1] === g &&
pixels.data[i+2] === b) {
amount++;
}
}
return amount;
}
@marcusklaas
Copy link

extremely elementary helpers though -- any adapt js programmer could write this in a couple of minutes

@mcjim
Copy link

mcjim commented May 23, 2013

@marcusklaas Some of us like saving minutes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment