首页 > 解决方案 > 无法让 ColorThief 在 Angular 中正常工作,找不到库方法?

问题描述

我正在尝试在 Angular 12 项目中使用 Library ColorThief(https://lokeshdhakar.com/projects/color-thief/),但没有成功让它工作。我从做开始$ npm i --save colorthief,然后在我想要的组件 .ts 文件中:
const ColorThief = require('colorthief');.

一切都正确编译,但某些方法在浏览器中触发时无法识别。

我也尝试将脚本标签添加到我的 index.html 文件中,但没有成功。

我的组件 TS 文件:

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

有人知道我做错了什么吗?或者在 Angular 中成功使用 ColorThief 的人?

标签: angulartypescriptimportcolor-thiefangular12

解决方案


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

推荐阅读