安装:
npm i --save colorthief
使用:
ImgColor() {
let domImg = document.querySelector('#background'); // 获取图片dom节点
let colorthief = new ColorThief();
domImg.addEventListener('load', () => { // 图片加载
this.colors = colorthief.getPalette(domImg).map(e => {
let hex = this.rgbaToHex(e)
return hex
}); // 调色板
this.zcolor = this.rgbaToHex(colorthief.getColor(domImg)) // 图片主色调
console.log('调色盘', this.colors);//getPalette(domImg, 2)第二个参数可选(1~10)
console.log('主色调', this.zcolor);//第二个参数可选(1~10)
})
},
rgbaToHex(rgba) { // rgba转16进制
let hex = '#';
for (const i of rgba) {
hex += i.toString(16).padStart(2, '0');
}
return hex;
},
运行示例:

更多用法参见官网:Color Thief