Check out this screenshot to see what I'm aiming for.
I discovered a solution online that might help me achieve my goal.
To test the solution, I set up a simple HTML structure like this:
<div id="block">
<img
id="img" class="cimg" src=
"http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>
<div id="block">
<img
id="img" class="cimg" src=
"http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>
<div id="block">
<img
id="img" class="cimg" src=
"http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>
Here's the Javascript code I used:
function averageColor(imageElement) {
// Create canvas element
var canvas
= document.createElement('canvas'),
// Get 2D canvas context
context
= canvas.getContext &&
canvas.getContext('2d'),
imgData, width, height,
length,
// Store individual color values
rgb = { r: 0, g: 0, b: 0 },
// Total number of colors
count = 0;
// Set canvas height and width
height = canvas.height =
imageElement.naturalHeight ||
imageElement.offsetHeight ||
imageElement.height;
width = canvas.width =
imageElement.naturalWidth ||
imageElement.offsetWidth ||
imageElement.width;
// Draw image on canvas
context.drawImage(imageElement, 0, 0);
// Get image data
imgData = context.getImageData(
0, 0, width, height);
// Get image data length
length = imgData.data.length;
for (var i = 0; i < length; i += 4) {
// Sum red color values
rgb.r += imgData.data[i];
// Sum green color values
rgb.g += imgData.data[i + 1];
// Sum blue color values
rgb.b += imgData.data[i + 2];
// Increment total color values count
count++;
}
// Calculate average color values
rgb.r
= Math.floor(rgb.r / count);
rgb.g
= Math.floor(rgb.g / count);
rgb.b
= Math.floor(rgb.b / count);
return rgb;
}
// Function to set background color of div
var rgb;
setTimeout(() => {
rgb = averageColor(
document.getElementById('img'));
// Select element and set background color
document
.getElementById("block")
.style.backgroundColor =
'rgb(' + rgb.r + ','
+ rgb.g + ','
+ rgb.b + ')';
}, 500)
Essentially, I created divs containing images and used Javascript to apply backgrounds. However, this method only worked on the first div and not the others. I tried using a loop without success:
var rgb;
var imgg = document.getElementsByClassName("card1");
var i;
for (i = 0; i < imgg.length; i++) {
rgb = averageColor(document.getElementById('img'));
// Select element and set its background color
document
.getElementById("block")
.style.backgroundColor =
'rgb(' + rgb.r + ','
+ rgb.g + ','
+ rgb.b + ')';
}
If anyone has any ideas or solutions, please let me know!