Skip to content

Instantly share code, notes, and snippets.

Created July 19, 2014 14:08
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 anonymous/605192c9481c963c7d7c to your computer and use it in GitHub Desktop.
Save anonymous/605192c9481c963c7d7c to your computer and use it in GitHub Desktop.
A rather unoptimised colour averaging algorithm from an image trianglifier for a blog post over at https://starbeamrainbowlabs.com
function getaveragepixelcolour(pixeldata, width, height, x, y, radius)
{
var colours = [];
for(var cx = x - radius; cx < x + radius; cx++)
{
for(var cy = y - radius; cy < y + radius; cy++)
{
if(cx < 0 || cy < 0)
continue;
if(cx >= width || cy >= height)
continue;
colours.push(getpixelcolour(pixeldata, width, cx, cy));
}
}
var colour = { r: 0, g: 0, b: 0, a: 255};
for(var i = 0; i < colours.length; i++)
{
colour.r += colours[i].r;
colour.g += colours[i].g;
colour.b += colours[i].b;
colour.a += colours[i].a;
}
colour.r /= colours.length + 1;
colour.g /= colours.length + 1;
colour.b /= colours.length + 1;
colour.a /= colours.length + 1;
colour.r = Math.floor(colour.r);
colour.g = Math.floor(colour.g);
colour.b = Math.floor(colour.b);
colour.a = Math.floor(colour.a);
return colour;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment