A/E

Cover image for How to get dominant colour of an image with the Color Thief library in JavaScript​​​​‌‍​‍​‍‌‍‌​‍‌‍‍‌‌‍‌‌‍‍‌‌‍‍​‍​‍​‍‍​‍​‍‌​‌‍​‌‌‍‍‌‍‍‌‌‌​‌‍‌​‍‍‌‍‍‌‌‍​‍​‍​‍​​‍​‍‌‍‍​‌​‍‌‍‌‌‌‍‌‍​‍​‍​‍‍​‍​‍‌‍‍​‌‌​‌‌​‌​​​‍‍​‍​‍‌‍​‌‍‌‍​‌‍​‌‌‍​‌‍‍​‌‍‌​‌‌​​‍‍​​​​​​​​​‍‌‍‍‌‌‍‍‌‌​‌‍‌‌‌‍‍‌‌​​‍‌‍‌‌‌‍‌​‌‍‍‌‌‌​​‍‌‍‌‌‍‌‍‌​‌‍‌‌​‌‌​​‌​‍‌‍‌‌‌​‌‍‌‌‌‍‍‌‌​‌‍​‌‌‌​‌‍‍‌‌‍‌‍‍​‍‌‍‍‌‌‍‌​​‌‌‍‌‌​‌‍​‌​‌‍‌‌​​‍​‌​​‌‌‍‌‌​‍‌​‍‌​​​‌‍​‌‍‌​​‍‌​‌​​‌​​​​​‍​​‍‌​‍‌​‍​‌‍​‌‍‌​​‍‌‌‍‌‍​‌‌​​‌‌‍​‍‌‍‌‌​‌​‌‍‌‌​‍‌​‌‌‌‍​​​​‌‍​‍​‍‌‌​‌‍‌‌​​‌‍‌‌​‌‌​​‌‍‌​‌‌​​‍‌​​‌‍​‌‌‌​‌‍‍​​‌‌‌​‌‍‍‌‌‌​‌‍​‌‍‌‌​‌‍​‍‌‍​‌‌​‌‍‌‌‌‌‌‌‌​‍‌‍​​‌‌‍‍​‌‌​‌‌​‌​​​‍‌‌​​‌​​‌​‍‌‌​​‍‌​‌‍​‍‌‌​​‍‌​‌‍‌‍​‌‍‌‍​‌‍​‌‌‍​‌‍‍​‌‍‌​‌‌​​‍‌‌​​‌​​‌​​​​​​​​​‍‌‍‌‍‍‌‌‍‌​​‌‌‍‌‌​‌‍​‌​‌‍‌‌​​‍​‌​​‌‌‍‌‌​‍‌​‍‌​​​‌‍​‌‍‌​​‍‌​‌​​‌​​​​​‍​​‍‌​‍‌​‍​‌‍​‌‍‌​​‍‌‌‍‌‍​‌‌​​‌‌‍​‍‌‍‌‌​‌​‌‍‌‌​‍‌​‌‌‌‍​​​​‌‍​‍​‍‌‍‌‌​‌‍‌‌​​‌‍‌‌​‌‌​​‌‍‌​‌‌​​‍‌‍‌​​‌‍​‌‌‌​‌‍‍​​‌‌‌​‌‍‍‌‌‌​‌‍​‌‍‌‌​‍​‍‌‌

We have all seen many designs, music players in particular dynamically changing design properties according to the dominant colour (ahem 'color') of an image.

Spotify does it, Deezer does it, Youtube Music does it, and I recently did it to showcase my 2022 Spotify playlist Here. Now let's do it too!.

We start with a basic boilerplate

Basic boilerplate

Then we'll code ourselves a simple HTML and CSS webpage with the Color Thief CDN link

(also available on NPM npm i --save colorthief)

HTML

HTML

CSS

CSS

So we should be left with a nice randomly generated kitten page

Kitten page

Now for the fun part, Javascript!

JS

Don't worry, I'll explain the javascript part

First we make sure our page is fully loaded by wrapping our code in the window.onload function

JS

Then we'll get our image and the background element

JS

Next, we'll initialize colorthief and get the color palette of the image

JS

Set the background color to the RBG value of the palette

JS

Then we'll call the function

JS

everything together should look like this

JS

Our page should now be working!.

working kitty page

Hurray!

hurray

Any suggestions or issues, feel free to comment and follow me lol.​​​​‌‍​‍​‍‌‍‌​‍‌‍‍‌‌‍‌‌‍‍‌‌‍‍​‍​‍​‍‍​‍​‍‌​‌‍​‌‌‍‍‌‍‍‌‌‌​‌‍‌​‍‍‌‍‍‌‌‍​‍​‍​‍​​‍​‍‌‍‍​‌​‍‌‍‌‌‌‍‌‍​‍​‍​‍‍​‍​‍‌‍‍​‌‌​‌‌​‌​​​‍‍​‍​‍‌‍​‌‍‌‍​‌‍​‌‌‍​‌‍‍​‌‍‌​‌‌​​‍‍​​​​​​​​​‍‌‍‍‌‌‍‍‌‌​‌‍‌‌‌‍‍‌‌​​‍‌‍‌‌‌‍‌​‌‍‍‌‌‌​​‍‌‍‌‌‍‌‍‌​‌‍‌‌​‌‌​​‌​‍‌‍‌‌‌​‌‍‌‌‌‍‍‌‌​‌‍​‌‌‌​‌‍‍‌‌‍‌‍‍​‍‌‍‍‌‌‍‌​​‌‌‍‌‌​‌‍​‌​‌‍‌‌​​‍​‌​​‌‌‍‌‌​‍‌​‍‌​​​‌‍​‌‍‌​​‍‌​‌​​‌​​​​​‍​​‍‌​‍‌​‍​‌‍​‌‍‌​​‍‌‌‍‌‍​‌‌​​‌‌‍​‍‌‍‌‌​‌​‌‍‌‌​‍‌​‌‌‌‍​​​​‌‍​‍​‍‌‌​‌‍‌‌​​‌‍‌‌​‌‌​​‌‍‌​‌‌​​‍‌​​‌‍​‌‌‌​‌‍‍​​‌‌‍​‍‌‍‌‍‌​‌‍‌​‌‍​‍‌‍​‌‌​‌‍‌‌‌‌‌‌‌​‍‌‍​​‌‌‍‍​‌‌​‌‌​‌​​​‍‌‌​​‌​​‌​‍‌‌​​‍‌​‌‍​‍‌‌​​‍‌​‌‍‌‍​‌‍‌‍​‌‍​‌‌‍​‌‍‍​‌‍‌​‌‌​​‍‌‌​​‌​​‌​​​​​​​​​‍‌‍‌‍‍‌‌‍‌​​‌‌‍‌‌​‌‍​‌​‌‍‌‌​​‍​‌​​‌‌‍‌‌​‍‌​‍‌​​​‌‍​‌‍‌​​‍‌​‌​​‌​​​​​‍​​‍‌​‍‌​‍​‌‍​‌‍‌​​‍‌‌‍‌‍​‌‌​​‌‌‍​‍‌‍‌‌​‌​‌‍‌‌​‍‌​‌‌‌‍​​​​‌‍​‍​‍‌‍‌‌​‌‍‌‌​​‌‍‌‌​‌‌​​‌‍‌​‌‌​​‍‌‍‌​​‌‍​‌‌‌​‌‍‍​​‌‌‍​‍‌‍‌‍‌​‌‍‌​‍​‍‌‌

Alternate Error