<body>
<h1>Average Color of an Image</h1>
<p>Drop an image in the box below to get the average color of it in RGB values! </p>
<div id="dropBox" ondrop="drop(event)" ondragover="drag(event)" > <p>Drop your image here! :)</p> </div>
<div id="images"></div>
<div class="colorBox"> </div>
</body>
function addImage(file) {
img.src = URL.createObjectURL(file);
var hue = document.querySelector(".colorBox");
img.onload = function () {
var rgb = averageColor(img);
var rgbString = "rgb(" + r + " , "+ g + ", " + b + ")";
rgb.innerHTML="";
//I used querySelector to grab the class .colorBox that will hold the rgb avrg. color value
hue.style.backgroundColor = rgbString;
}
document.getElementById('images').appendChild(hue);
}
function averageColor(img) {
//I create canvas and set the width and height of it to that of the image
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width = img.naturalWidth;
var height = canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
var imageData = ctx.getImageData(0, 0, width, height);
var data = imageData.data;
var r = 0; //I set the rgb values to 0 for non supporting browsers
var g = 0;
var b = 0;
//loop over each pixel
for (var i = 0, l = data.length; i < l; i += 4) {
r += data[i];
g += data[i+1];
b += data[i+2];
}
//get the average values for rgb using Math.floor
r = Math.floor(r / (data.length / 4));
g = Math.floor(g / (data.length / 4));
b = Math.floor(b / (data.length / 4));
return { r: r, g: g, b: b };
}
//create the drag and drop zone..
function drag(event) {
event.stopPropagation();
event.preventDefault();
//event.dataTransfer.setData;
event.dataTransfer.dropEffect = "copy"; //this property will copy the image to the new location
}
function drop(event) {
event.stopPropagation();
var img = event.dataTransfer.createObjectURL(file);
event.dropBox.appendChild(document.getElementById(img)); //append the dragged
//image into the drop zone
document.getElementById("images").innerHTML = '';
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.