Grab the Dominant Color Of Image with jQuery

November 11, 2017 by Andreas Wik

For a profile page template I was designing recently I needed a way to pick a color that would work well together with the user’s profile photo. Now, this can obviously not be done manually as users will upload their profile photo themselves, so this color needs to be generated dynamically.

Luckily, Mr Lokesh Dhakar has built a neat little jQuery plugin called Color Thief, which simply gives you the dominant color of your choosen image, or, if you need more than one, a palette of colors.

I put together this little demo. You can download it here (zip).

Now, let’s play!

Go grab a copy of jQuery and Color Thief and include them on your page. Also add your image.

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <img id="my-img" src="img/forest.jpg">
 
        <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
        <script src="js/color-thief/src/color-thief.js"></script>
    </body>
</html>

 

Next, let’s create the colorThief object and grab the dominant color of the image.

// Create colorThief object
var colorThief = new ColorThief();
 
// Make sure everything is loaded
$(window).load(function() {
 
  // Get image
  var sourceImage = $('#my-img')[0];
 
  // Get the dominant color of image
  color = colorThief.getColor(sourceImage);
 
  // Use the new color as background for body
  $('body').css('background-color', 'rgb(' + color + ')');
});

 

As you can see I wrapped the jQuery function .load around it. Why? Because in case your image is not loaded before you call the getColor function, you will be presented with this nasty error in the console:

Uncaught DOMException: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’

There are many ways to do this, and you might want to only wait for that specific image to load rather than the whole page as I do here.

 

Using external images

If you use an external image (not hosted on your domain), then there’s quite a big risk that you run into the following error:

Uncaught DOMException: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’: The canvas has been tainted by cross-origin data.
at CanvasImage.getImageData

Make sure that the server where the image is hosted provides the necessary Allow-Control-Allow-Origin header to allow you doing this. Or, just use local images if you can and you’ll have one thing less to worry about.

 

Palette of colors

Color Thief also lets you grab a palette of representative colors of the image. Let’s get a palette of four from our image:

// Get palette of 4 colors of image
var palette = colorThief.getPalette(sourceImage, 4);
 
// Fill palette container with palette colors
for(var i = 0; i < palette.length; i++) {
 
  $('#palette').append('<div class="palette-color" style="background-color: rgb('+palette[i]+');"></div>');
}

 

Final code

Let’s wrap this up. Check out the result. You can download it here.

Final code:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Dominant Color</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
 
        <style>
          #my-img {
            display: block;
            margin: 10px auto;
          }
 
          #palette {
            display: block;
            text-align: center;
          }
 
          .palette-color {
            width: 30px;
            height: 30px;
            margin: 5px;
            display: inline-block;
            background-color: #ffffff;
            border: 2px solid #000000;
          }
        </style>
    </head>
    <body>
 
        <img id="my-img" src="img/forest.jpg">
        <div id="palette">
        </div>
 
        <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
        <script src="js/color-thief/dist/color-thief.min.js"></script>
        <script>
 
          // Create colorThief object
          var colorThief = new ColorThief();
 
          // Make sure everything is loaded
          $(window).load(function() {
 
            // Create image object
            var sourceImage = $('#my-img')[0];
 
            // Get the dominant color of image
            var color = colorThief.getColor(sourceImage);
 
            // Use the new color as background for body
            $('body').css('background-color', 'rgb(' + color + ')');
 
            // Get palette of 4 colors of image
            var palette = colorThief.getPalette(sourceImage, 4);
 
            // Fill palette container with the colors
            for(var i = 0; i < palette.length; i++) {
 
              $('#palette').append('<div class="palette-color" style="background-color: rgb('+palette[i]+');"></div>');
            }
          });
 
        </script>
    </body>
</html>

Have you built something awesome using Color Thief? Share it in the comments below!

Happy coding!

Share this article

Recommended articles