微信小程序获取图片主色

601 阅读1分钟

1.需要安装miniapp-color-thief

import colorThief from "miniapp-color-thief"

Page({
  // 获取主色
  getMainColor(src) {
    const ctx = wx.createCanvasContext('myCanvas', this);
    return new Promise((resolve) => {
      wx.getImageInfo({
        src,
        success(imgInfo) {
          const { path, height, width } = imgInfo;
          ctx.drawImage(path, 0, 0, 300, 150)
          ctx.draw(false, () => {
            wx.canvasGetImageData({
              canvasId: "myCanvas", x: 0, y: 0, width, height,
              success: res => {
                const palette = colorThief(res.data).palette().getHex();
                resolve(palette)
              }
            });
          })
        },
        fail(err) { console.error(err); }
      })
    })
  },
  async onReady() {
    const color = await this.getMainColor("https://avatars.githubusercontent.com/u/103183121?s=40&v=4")
    console.log(
      "color", color
    );
  }
})