uniapp 开发微信小程序
我想实现点击一个按钮,将一个网络图片切割成九宫格形式的图片,然后保存到手机相册
代码如下,但是报错choiceness.js? [sm]:172 canvasToTempFilePath 失败 {errMsg: "canvasToTempFilePath:fail fail canvas is empty"}(env: macOS,mp,1.06.2308310; lib: 3.1.5)
<view class="img-list" @click="handleclick">
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance();
const handleclick = () => {
const ctx = uni.createCanvasContext('myCanvas', instance);
// 获取图片信息
uni.getImageInfo({
src: 'https://xxxxxxxx'
success: (info) => {
// 计算每个小格子的宽度和高度
const cellWidth = info.width / 3;
const cellHeight = info.height / 3;
// 绘制九宫格
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
ctx.drawImage(
bigImg.value.org_url,
col cellWidth, row cellHeight, cellWidth, cellHeight,
col cellWidth, row cellHeight, cellWidth, cellHeight
);
}
}
ctx.draw(false, setTimeout(() => {
console.log(ctx, instance)
// 将Canvas内容保存为临时文件路径
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (imageInfo) => {
// 保存到手机相册
uni.saveImageToPhotosAlbum({
filePath: imageInfo.tempFilePath,
success: () => {
setTimeout(() => { uni.showToast({ title: '保存成功', icon: 'success', duration }) }, 10)
},
});
},
}, instance);
}, 1000));
}
});
}
1 个回复
最佳回复
爱豆豆 - 办法总比困难多
微信官方文档中标明 canvas当使用2d时不用传参 canvasId,直接传入canvas实例即可。
参考文档:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasToTempFilePath.html
改变下写法即可 参考下方示例