How to get dominant colour of an image with the Color Thief library in JavaScript
Get the dominant color of any image using the color thief library in javascript and create nice ui experiences.
Time to read: ~ 4 min
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
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
CSS
So we should be left with a nice randomly generated kitten page
Now for the fun part, Javascript!
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
Then we'll get our image and the background element
Next, we'll initialize colorthief and get the color palette of the image
Set the background color to the RBG value of the palette
Then we'll call the function
everything together should look like this
Our page should now be working!.
Hurray!
Any suggestions or issues, feel free to comment and follow me lol.