Reputation: 329
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
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
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