Skip to content

Instantly share code, notes, and snippets.

@vdchristelle
Created September 9, 2013 07:28
Show Gist options
  • Save vdchristelle/6492469 to your computer and use it in GitHub Desktop.
Save vdchristelle/6492469 to your computer and use it in GitHub Desktop.
Calculate the brighness of the image and change color of another element e.g. banner text
/**
* jQuery function will convert each color to gray scale and return average of all pixels, so final value will be between 0 (darkest) and 255 (brightest){Object} $
* docu: http://stackoverflow.com/questions/13762864/image-dark-light-detection-client-sided-script
* docu: http://jsfiddle.net/s7Wx2/7/
*/
(function ($) {
//darkness of picture
function getImageLightness(imageSrc,callback) {
var img = document.createElement("img");
img.src = imageSrc;
img.style.display = "none";
document.body.appendChild(img);
var colorSum = 0;
img.onload = function() {
// create canvas
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this,0,0);
var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
var data = imageData.data;
var r,g,b,avg;
for(var x = 0, len = data.length; x < len; x+=4) {
r = data[x];
g = data[x+1];
b = data[x+2];
avg = Math.floor((r+g+b)/3);
colorSum += avg;
}
var brightness = Math.floor(colorSum / (this.width*this.height));
callback(brightness);
}
}
$(document).ready(function() {
//loop checks brightness of the banner picture and adjust the color of the text accordingly
$('#REPLACE_WITH_YOUR_ID ul.slides li').each(function(){
var $image = $(this).find('img');
var $imageUrl = $image.attr('src');
getImageLightness($imageUrl,function(brightness){
console.log($imageUrl+' : '+brightness);
console.log($image);
if(brightness>180){
$image.parents('li:first').find('.homeslidertext').addClass('darktext');
console.log($image.parents('li:first').find('.homeslidertext').attr('class'));
brightness = 0;
}
});
});
});
Drupal.behaviors.website = {
attach : function(context) {
// put your contextual goodyness in here
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment