npm i --save colorthief
<template> <div> <img :src="coverLarge" crossorigin="anonymous" alt="" /> </div> </template> <script> import ColorThief from 'colorthief' export default { data () { return { coverLarge:'', }; }, methods: { ImgColor() { let domImg = document.querySelector('img'); // 获取图片dom节点 let colorthief = new ColorThief(); domImg.addEventListener('load', () => { // 图片加载 console.log('主色调', this.rgbaToHex(colorthief.getColor(domImg)));//图片主色调,第二个参数可选(1~10) }) }, rgbaToHex(rgba) { // rgba转16进制 let hex = '#'; for (const i of rgba) { hex += i.toString(16).padStart(2, '0'); } return hex; }, getMusicList () { return new Promise((resolve, reject) => { let sData = {} songInfo(sData).then(response => { const { data: res } = response this.coverLarge = res.data.coverLarge this.$nextTick(() => { this.ImgColor() }) }) resolve(true) }).catch(() => { reject(false) }) }, }, mounted () { this.getMusicList() }, }; </script>
如果报错:The canvas has been tainted by cross-origin data.
说明跨域了,需要给图片设置属性:crossorigin="anonymous"