ColorThief.getColor is not a function

1.8k Views Asked by At

So, i'm trying to get my dominant color from color thief. But i'm constantly getting this error:

enter image description here

Here is my code that I took from the official documentation

var ColorThief = require('colorthief');

// if I don't include this I will get an error that resolve is not defined
const { resolve } = require('path');
 const setMarker = ({ data }) => {

        // this returns a string with the url to the logo
        const logo = data.logo ? data.logo : LogoPlaceholder

        const img = resolve(process.cwd(), logo);

        ColorThief.getColor(img)
            .then(color => { console.log(color) })
            .catch(err => { console.log(err) })
}

Anyone has anidea how to get this working?

EDIT : Maybe a key thing to know is that I'm not letting the images load in my website, I only need the colours of them

2

There are 2 best solutions below

1
ksav On
import React, { createRef } from "react";
import "./styles.css";
import ColorThief from "colorthief";

export default function App() {
  const imgRef = createRef();

  return (
    <div className="App">
      <img
        crossOrigin={"anonymous"}
        ref={imgRef}
        alt="my cool cat"
        src="https://placekitten.com/408/287"
        onLoad={() => {
          const colorThief = new ColorThief();
          const img = imgRef.current;
          const result = colorThief.getColor(img, 25);
          console.log(result);
        }}
      />
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Edit wonderful-lamarr-ej8w7

0
Chinedu Etoh On
import ColorThief from 'colorthief'

  ngOnInit(){

    const img = document.querySelector('img');

    const colorThief = new ColorThief();

    if (img.complete) {
     // colorThief.getColor(img);
      this.mopl = colorThief.getColor(img)
    } else {
      img.addEventListener('load', () => {
       // colorThief.getColor(img);
        this.mopl = colorThief.getColor(img)
      });
    }
}