Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple example to load color from JS #207

Open
Elkaroui opened this issue May 20, 2021 · 1 comment
Open

Simple example to load color from JS #207

Elkaroui opened this issue May 20, 2021 · 1 comment

Comments

@Elkaroui
Copy link

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
Copy link

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);
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants