lokesh / color-thief

Grab the color palette from an image using just Javascript. Works in the browser and in Node.
https://lokeshdhakar.com/projects/color-thief/
MIT License
12.34k stars 1.31k forks source link

Simple example to load color from JS #207

Open Elkaroui opened 3 years ago

Elkaroui commented 3 years ago

Hello, my knowledge of JS script is not so good, I had read the documentation but I couldn't understand it, could please give some simples to pick the colors from the image inside the JS, like this example, I had tried it but nothing happens because I don't know how to pick the color and add it to div element for example with a class

const colorThief = new ColorThief();
const img = new Image();

img.addEventListener('load', function() {
  colorThief.getColor(img);
};

img.crossOrigin = 'Anonymous';
img.src = 'https://aws.com/s3/image.jpeg'

Sorry guys I am now JS and still so confusing, 🙏🙏🙏

caplock221b commented 2 years ago

Hi @Elkaroui! A bit late but I wanted to answer this question anyways for all the new JS developers out there who are facing the same issue. The docs don't make it very clear how to use it like you mentioned. The getColor(img) function returns an array containing three values - the red, green and blue value for the image's dominant color. You can use it in the following way:

img.addEventListener('load', function(){
    // Get r, g, b values from getColor() function
    const [r, g, b] = colorThief.getColor(img);

    // Create a div with a class name
    const div = document.createElement("div");

    // Set the class name for the div
    div.className = "dummy";

    // Set the inner text value for the div
    div.innerText = "Dummy Text";

    // Set the background color for the div
    div.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;

    // Append the newly created div to the body
    document.body.appendChild(div);
})