Skip to content

Instantly share code, notes, and snippets.

@jcsrb
Created January 13, 2012 18:21
Show Gist options
  • Select an option

  • Save jcsrb/1607885 to your computer and use it in GitHub Desktop.

Select an option

Save jcsrb/1607885 to your computer and use it in GitHub Desktop.
// taken from https://github.com/lokesh/color-thief
/*
CanvasImage Class
Class that wraps the html image element and canvas.
It also simplifies some of the canvas context manipulation
with a set of helper functions.
*/
var CanvasImage = function(image){
// If jquery object is passed in, get html element
this.imgEl = (image.jquery)? image[0]: image;
this.canvas = document.createElement('canvas'),
this.context = this.canvas.getContext('2d');
document.body.appendChild(this.canvas);
this.width = this.canvas.width = $(this.imgEl).width(),
this.height = this.canvas.height = $(this.imgEl).height();
this.context.drawImage(this.imgEl, 0, 0);
}
CanvasImage.prototype.clear = function() {
this.context.clearRect(0, 0, this.width, this.height);
}
CanvasImage.prototype.update = function(imageData) {
this.context.putImageData(imageData, 0, 0);
}
CanvasImage.prototype.getPixelCount = function() {
return this.width * this.height;
}
CanvasImage.prototype.getImageData = function() {
return this.context.getImageData(0, 0, this.width, this.height);
}
CanvasImage.prototype.removeCanvas = function() {
$(this.canvas).remove();
}
/*
* getAverageRGB(sourceImage)
* returns {r: num, g: num, b: num}
*
* Add up all pixels RGB values and return average.
* Tends to return muddy gray/brown color. Most likely, you'll be better
* off using getDominantColor() instead.
*/
function getAverageRGB(sourceImage) {
// Config
var sampleSize = 10;
// Create custom CanvasImage object
var image = new CanvasImage(sourceImage),
imageData = image.getImageData(),
pixels = imageData.data,
pixelCount = image.getPixelCount();
// Reset vars
var i = 0,
count = 0,
rgb = {r:0,g:0,b:0};
// Loop through every # pixels. (# is set in Config above via the blockSize var)
// Add all the red values together, repeat for blue and green.
// Last step, divide by the number of pixels checked to get average.
while ( (i += sampleSize * 4) < pixelCount ) {
// if pixel is mostly opaque
if(pixels[i+3] > 125){
++count;
rgb.r += pixels[i];
rgb.g += pixels[i+1];
rgb.b += pixels[i+2];
}
}
rgb.r = Math.floor(rgb.r/count);
rgb.g = Math.floor(rgb.g/count);
rgb.b = Math.floor(rgb.b/count);
return rgb;
}
$("article").each(function(index,element){
var image = $(element).find("img").first();
var colorString = "rgb("+getAverageRGB(image).r+","+getAverageRGB(image).g+","+getAverageRGB(image).b+")";
console.log(colorString);
$(element).find(".more-link").css({"background-color":colorString});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment