包括下载包,简单使用都有,之前写了,这里就不写了 网址:微信小程序的图片色彩分析,窃取主色调,调色板-CSDN博客
export default (url, path = "") => {
return new Promise((resolve, reject) => {
const fs = wx.getFileSystemManager()
// 判断文件/目录是否存在
fs.access({
path,
success(res) {
// 文件存在,复用
console.log(res)
resolve(path)
},
fail(res) {
// 文件不存在或其他错误,下载为临时文件
console.log(res)
wx.downloadFile({
url,
success(res) {
if (res.statusCode === 200) {
resolve(res.tempFilePath)
wx.setStorageSync('bgcUrl', res.tempFilePath)
}
},
fail: (err) => {
reject(err)
}
})
}
})
})
}
注意:wxml中需要放置
<canvas canvas-id="myCanvas" />
import downloadFile from '../../utils/downloadFile'
Page({
data: {
palette: "",
// 用户信息
userInfo: {},
},
// 判断是否有背景图片的缓存文件,没有就下载为临时文件,最后绘画出来
async bgcDownload() {
let bgcUrl = wx.getStorageSync('bgcUrl')
let result = await downloadFile(this.data.userInfo.backgroundUrl, bgcUrl)
console.log(result);
const ctx = wx.createCanvasContext('myCanvas')
ctx.drawImage(result, 0, 0, 100, 100);
ctx.draw(false, () => {
wx.canvasGetImageData({
canvasId: "myCanvas",
x: 0,
y: 0,
width: 100,
height: 100,
success: res => {
let palette = colorThief(res.data).color().getHex();
this.setData({ palette })
}
});
})
},
onReady: function () {
this.bgcDownload()
},
})