JSFiddle - React, Tailwind, and code Playground

by Reem Al Dossary

HTML

<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>

CSS

@charset "UTF-8";
/* CSS Document */
body {
	margin: auto;	
	
}

h1 {
	font-family: Verdana, Geneva, sans-serif;
	font-size: 24px;
	color: #036;
	text-align: center;
	font-weight: bold;
}

p {
	font-family: Verdana, Geneva, sans-serif;
	font-size: 12px;
	color: #000;
	text-align: center;
}
.colorBox {
	height: 100px;
	width: 300px;
	margin-top: 50px;
	margin-right: auto;
	margin-bottom: auto;
	margin-left: auto;
	border: 1px solid #CCC;
}
#dropBox {
	height: 200px;
	width: 500px;
	background-color: #FFF;
	border: 2px dashed #CCC;
	margin: auto;
}

JavaScript

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 = '';
            
  }