Anjali
Anjali

Reputation: 329

can not loop for getting average image color

i want to get all three image background color in the <p> text color but unable to loop this how to loop this all images and into one , i have three images i just want to loop this three images color.

here - http://jsfiddle.net/xLF38/4346/

thanks to @james for this amazing answer Get average color of image via Javascript but only supports id i want class wise

Upvotes: 0

Views: 51

Answers (2)

barbsan
barbsan

Reputation: 3458

Just get target elements by class in same way you've retrieved nodes with image class.

var r = document.getElementsByClassName('image');
var targets = document.getElementsByClassName('imagecolor');
var p ;
for (p = 0 ; p < r.length ; p++ ){
   var rgb = getAverageRGB(r[p]);
   targets[p].style.color = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')';
}

For better performance avoid having in loop's body both read DOM and write DOM operations (use separate loops). Demo

var r = document.getElementsByClassName('image');
var targets = document.getElementsByClassName('imagecolor');
var rgb = [];
for (p = 0 ; p < r.length ; p++ ){
   rgb.push(getAverageRGB(r[p]));
}
rgb.forEach((el,i) => {
   targets[i].style.color = 'rgb('+el.r+','+el.g+','+el.b+')';
})

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138447

Just go over all images and build the average:

 const images = [...document.querySelectorAll(".someclass")];

 const result = { r: 0, g: 0, b: 0 };

 for(const image of images) {
   const {r, g, b} = getAverageRGB(image);
   result.r += r / images.length;
   result.g += g / images.length; 
   result.b += b / images.length;
 }

Upvotes: 0

Related Questions