Recently I have created Background-Color-Theif.js. In this article You can find logic behind this script.

Lets define background color first. Observe the below Image with plain background. Here main image was centered and background color was spread all over edges and corners of the image. Most of images have background color spread to corners and edges. So we can say " Most dominant color of edges and corners is the background color of the image " 
Lets Consider 10% of width of an Image ( both Left and Right side of image ) are vertical edges,  10% of height of an Image ( both Top and Bottom side of image ) are horizontal edges. Finally the selected areas of image will look like below image.


Background-Color-Theif.js is for grabbing background color of an image. This code consists some code snippets from Color-Theif.js 

Top and Bottom edges

Below image is having size of 300 X 200.  You can see pixel count values in small rectangular boxes.
These edges covers corners also, So no need to retrieve corners pixel values.

Side Edges

You can find pixel count values of Left and Right edges below.
Get all pixel values from corners and edges and find dominant color of it and that color will be background color of image

How to use

Add script to your HTML page

<script src="background-color-theif.js" type="text/javascript"></script>

Define HTML markup

<img src="source.jpg" id="backgroundImage"/>
<div id="backGroundColor"></div>


var backgroundColorThief = new BackgroundColorTheif();
var rgb = backgroundColorThief.getBackGroundColor(document.getElementById("backgroundImage"));
document.getElementById("backGroundColor").style.backgroundColor = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] +')';


I have implemented some online tools using this script. Take a look at below links


  1. How can be this use into angular2?

  2. How to use it with an image whose src is the url

  3. Code Ninja is one of the leading web development company. It has been excelling in the IT industry for the past 8 years whilst delivering numerous web development projects at competitive prices, having 100% satisfied customers all over the globe. This software house specializes in delivering complex custom web development agency, ecommerceplat forms, app development (iOS, Android, & Windows), Custom CRM Development, search engine optimization, and creative web design, shopify, magento technologies. CodeNinja is well reputed for delivering multifaceted IT Solutions across the world to a host of local and international clients.



Popular Posts