赞
踩
包括下载包,简单使用都有,之前写了,这里就不写了
- 问题:由于我们的窃取图片的是需要画布的,我需要使用网络图片去用画布时,微信小程序会报错,最后发现,需要本地图片才行,用网络图片会出问题
- 解决方案:我们使用wx.downloadFile去下载该图片,然后获取临时路径去使用画布和Mini App Color Thief 包 窃取图片颜色,防止图片重复下载的话,我们去用微信小程序中的另一个api,FileSystemManager.access(Object object)去判断临时文件是否存在
- 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)
- }
- })
- }
- })
- })
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
注意: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()
- },
- })
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。