Cannot get ColorThief to work correctly in Angular, library methods are not found?

915 Views Asked by At

I am trying to use the Library ColorThief(https://lokeshdhakar.com/projects/color-thief/) in an Angular 12 project but have had no success getting it to work. I started by doing $ npm i --save colorthief and then in my desired component .ts file:
const ColorThief = require('colorthief');.

Everything compiles correctly but some of the methods are not recognized when they are triggered in the browser.

I have also tried adding the script tag to my index.html file, with no success.

My Component TS file:

import { Color } from '../shared/model/color';
const ColorThief = require('colorthief');
//import ColorThief from 'angular-colorthief';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, AfterViewInit {
...
autoGeneratePalette(numColors:number) {
    this.userPalette = [];
      this.paletteCounter = 0;
    //var ColorThief:any = new ColorThief();
      ColorThief.getPalette(this.imgToUse, numColors)
      .then((palette: any) => {
      for(var i = 0; i < palette.length; i++) {
        var color = new Color(0,0,0,0);
        color.red = palette[i][0];
        color.green = palette[i][1];
        color.blue = palette[i][2];
        color.index = i;
        this.userPalette.push(color);
      }
    })
    .catch((err: any) => {console.log(err)});
    }
}

Anyone have any ideas what I am doing wrong? Or someone that has successfully used ColorThief in Angular?

1

There are 1 best solutions below

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