在写vue-music的时候,希望把song-list组件做成向qq音乐那样,背景颜色根据歌单封面变化。

使用canvas 的getImageData可以获取到图片的数据,包括rgba

但是canvas 存在跨域问题。因此服务器端需要设置响应头,并且客户端设置image.crossOrigin = 'anonymous'

实现方式如下:

const HOST = '...';
export function getImageColor (src) {
  var canvas = document.createElement('canvas')
  var context = canvas.getContext('2d')
  var image = new Image()
  image.crossOrigin = 'anonymous'
  image.src = `${HOST}/QQMusicAvatar?src=` + src
  var promise = new Promise((resolve, reject) => {
    image.onload = function () {
      var imgWidth = this.width
      var imgHeight = this.height
      canvas.width = imgWidth
      canvas.height = imgHeight
      context.drawImage(this, 0, 0, imgWidth, imgHeight)
      var imgData = context.getImageData(1, 1, 1, 1)
      resolve(imgData)
    }
  })
  return promise
}
// 接下来就可以在song-list 组件中调用getImageColor了
// 比如说
export default {
    ...
    created () {
        this._getImageColor();
    }
    methods: {
        _getImageColor () {
            getImageColor(this.focus.avatar)
              .then((imgData) => {
                this.bgColor = `rgb(${imgData.data[0]},${imgData.data[1]},${imgData.data[2]})`
                this.loadingComplete = true
                if (imgData.data[0] > 100 && imgData.data[1] > 100 && imgData.data[2] > 100) {
                  this.isDark = false
                }
              })
          },
    }
    ...
}