H5中获取图片中的主色调
let imgSrc = that.swiperList[index].picUrl;
let img = new Image();
img.onload = ()=> {
that.getImageMainColor(img, index);// 图片标记
}
img.src=imgSrc;
getImageMainColor(img, index){ let ctx = this.canvas.getContext('2d'); let r =null; let g =null; let b =null; ctx.drawImage(img, 0, 0) let imgData = (ctx.getImageData(0, 0, img.width, img.height)).data; let color =this.getMainColor(imgData); let backgroundColor = `rgba(${color})`; // 图片主色 // this.picMainColor.push({ // sort: index, // background: backgroundColor //}); // sessionStorage.setItem('picMainColor', JSON.stringify(this.picMainColor)); // let item = this.picMainColor.find(e=>e.sort == 0); // this.SET_CURRENT_MAIN_COLOR(item ? item.background : 'rgb(80, 135, 203)'); }, getMainColor(data) { const temp = {} const len = data.length let max = 0; let color = '' let i = 0 while(i < len) { if (data[i + 3] !== 0) { const k = `${data[i]}, ${data[i + 1]}, ${data[i + 2]}, ${(data[i + 3] / 255)}` temp[k] = temp[k] ? temp[k] + 1 : 1 if (temp[k] > max) { max = temp[k] color = k } } i += 4 } return color }