angular - 无法让 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 的人?
解决方案
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)
});
}
}
推荐阅读
- javascript - 在页面更改后将反应数据保留在反应中
- r - 在 ggplot (geom_line) 中手动调整线条颜色
- html - 如何在 R HTML UI 元素中为图像的全宽拉伸图像?
- c++ - 为什么 std::bit_width 为值 0 返回 0,它不应该返回 1 吗?
- python - Anaconda 阻止我的 discord.py 机器人工作
- excel - 调用 vba 函数时出现“需要对象”错误
- laravel - 在修补程序中执行 Laravel Factory 错误
- python - 如何在 utf-8 中保存名称的文件
- javascript - 是否可以将 html 表单数据传递给 python 脚本,然后将结果打印到网页
- c - 如何将指针分配给结构内的指针?