1、在微信小程序中创建包管理器 package.json
npm init -y
2、安装 Mini App Color Thief 包
npm i --save miniapp-color-thief
3、构建 npm
4、wxml
html
<canvas canvas-id="myCanvas"></canvas>
<button bindtap="chooseImage">chooseImage</button>
<view wx:for="{{ palette }}" wx:key="index">
<view style="width:32px;height:32px;background-color: {{ item }}"></view>
<text>{{ item }}</text>
</view>
5、js
javascript
data: {
palette: []
},
/*
获取图片的色板
colorThief(data).palette(count, quality).get(); // [[0,0,0],[0,0,0],[0,0,0]...]
{Number} count 返回色板的颜色数量 ( 1 < count < 256 )
{Number} quality 计算颜色的精度,默认为 10
*/
chooseImage() {
const ctx = wx.createCanvasContext('myCanvas')
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: res => {
ctx.drawImage(res.tempFilePaths[0], 0, 0, 300, 150)
ctx.draw(true, () => {
wx.canvasGetImageData({
canvasId: "myCanvas",
x: 0,
y: 0,
width: 100,
height: 100,
success: res => {
let palette = colorThief(res.data)
.palette(3, 10)
.getHex();
this.setData({ palette })
}
});
})
}
})
},