<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
title
>
Find Average Color of
image via JavaScript?
</
title
>
<
style
>
#img {
position: absolute;
top: 20%;
left: 25%;
}
#block {
position: absolute;
background-color: white;
height: 70px;
width: 70px;
left: 50%;
top: 25%;
}
</
style
>
</
head
>
<
body
>
<
img
height
=
"100px"
width
=
"150px"
id
=
"img"
src
=
"image_to_find_average_color.png"
>
<
div
id
=
"block"
></
div
>
<
script
>
function averageColor(imageElement) {
// Create the canvas element
var canvas
= document.createElement('canvas'),
// Get the 2D context of the canvas
context
= canvas.getContext &&
canvas.getContext('2d'),
imgData, width, height,
length,
// Define variables for storing
// the individual red, blue and
// green colors
rgb = { r: 0, g: 0, b: 0 },
// Define variable for the
// total number of colors
count = 0;
// Set the height and width equal
// to that of the canvas and the image
height = canvas.height =
imageElement.naturalHeight ||
imageElement.offsetHeight ||
imageElement.height;
width = canvas.width =
imageElement.naturalWidth ||
imageElement.offsetWidth ||
imageElement.width;
// Draw the image to the canvas
context.drawImage(imageElement, 0, 0);
// Get the data of the image
imgData = context.getImageData(
0, 0, width, height);
// Get the length of image data object
length = imgData.data.length;
for (var i = 0; i <
length
; i += 4) {
// Sum all values of red colour
rgb.r += imgData.data[i];
// Sum all values of green colour
rgb.g += imgData.data[i + 1];
// Sum all values of blue colour
rgb.b += imgData.data[i + 2];
// Increment the total number of
// values of rgb colours
count++;
}
// Find the average of red
rgb.r
=
Math
.floor(rgb.r / count);
// Find the average of green
rgb.g
=
Math
.floor(rgb.g / count);
// Find the average of blue
rgb.b
=
Math
.floor(rgb.b / count);
return rgb;
}
// Function to set the background
// color of the second div as
// calculated average color of image
var rgb;
setTimeout(() => {
rgb = averageColor(
document.getElementById('img'));
// Select the element and set its
// background color
document
.getElementById("block")
.style.backgroundColor =
'rgb(' + rgb.r + ','
+ rgb.g + ','
+ rgb.b + ')';
}, 500)
</
script
>
</
body
>
</
html
>