canvas获取图片主题色


export default {
    methods:{
        getColor(url){
            let self = this;
            let img = new Image();
            let canvas = '', context = '', pixelData = ''
            canvas = document.getElementById('colorCanvas');
            context = canvas.getContext('2d');
            img.src = url;
            img.onload = function () {
              canvas.width = img.width;
              canvas.height = img.height;
              context.clearRect(0, 0, canvas.width, canvas.height);
              context.drawImage(img, 0, 0);
              pixelData = context.getImageData(0, 0, img.width, img.height).data;
              //获取最多色值的方法
              const temp = {}
              const len = pixelData.length

              let max = 0;
              let color = ''
              let i = 0
              while (i < len) {
              if (pixelData[i + 3] !== 0) {
                  const k = `${pixelData[i]}, ${pixelData[i + 1]}, ${pixelData[i + 2]}, ${(pixelData[i + 3] / 255)}`
                   temp[k] = temp[k] ? temp[k] + 1 : 1
                   if (temp[k] > max) {
                     max = temp[k]
                     color = k
                   }
                 }
                 i += 4
              }

              // 取所有像素平均值的方法
              let r = 0, g = 0, b = 0
              for (let row = 0; row < img.height; row++) {
                for (let col = 0; col < img.width; col++) {
                  r += pixelData[(img.width * row + col) * 4]
                  g += pixelData[(img.width * row + col) * 4 + 1]
                  b += pixelData[(img.width * row + col) * 4 + 2]
                }
              }

              // 计算平均值
              r /= img.width * img.height
              g /= img.width * img.height
              b /= img.width * img.height

              // 将结果取整
              r = Math.round(r)
              g = Math.round(g)
              b = Math.round(b)
              let color1 = r + ',' + g + ',' + b
              console.log(color,color1)
            }

            
          };
        };
        
        
    }

其实这两种方法都不是很完美,第一种在碰到渐变色背景+固定颜色文字的时候就会取到文字的颜色了,第二种则是在碰到png透明背景图片时会取到偏黑的色值。

你可能感兴趣的:(前端,javascript,canvas)