引入image-main-color插件
import { getMainColor } from '../../utils/image-main-color.js'
setBackgroundColor() {
const ctx = wx.createCanvasContext('myCanvas')
const that = this
wx.getImageInfo({
src: `${that.data.imageSrc}`,
success: function (res) {
const poster = res.path
ctx.drawImage(poster, 100,100, 150, 100)
ctx.draw(false, () => {
wx.canvasToTempFilePath({
x: 100,
y: 100,
width: 150,
height: 100,
destWidth: 150,
destHeight: 100,
canvasId: "myCanvas",
success(res) {
let tempPath = res.tempFilePath
// 这种方式获取canvas区域隐含的像素数据
wx.canvasGetImageData({
canvasId: 'myCanvas',
x: 100,
y: 100,
width: 150,
height: 100,
success(res) {
const imageData = res.data
// 分区块,可以拓展性的求主要色板,用来做palette
let resImageObj = getMainColor(imageData)
const { defaultRGB } = resImageObj
const { r, g, b } = defaultRGB
let resBackground = `rgb(${r}, ${g}, ${b})`
// console.log('resBackground',resBackground)
that.setData({
resBackground
})
// ctx.setFillStyle(resBackground)
// ctx.fillRect(0, 0, 150, 100)
// ctx.draw()
},
})
},
fail() {
throw new Error()
}
})
})
},
fail() {
}
})
},