z***@163.com
z***@163.com
  • 发布:2023-12-11 14:20
  • 更新:2023-12-11 17:08
  • 阅读:1207

canvasToTempFilePath 失败 {errMsg: "canvasToTempFilePath:fail fail canvas is empty"}

分类:uni-app

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));

            }  
        });  

}

2023-12-11 14:20 负责人:无 分享
已邀请:

最佳回复

爱豆豆

爱豆豆 - 办法总比困难多

微信官方文档中标明 canvas当使用2d时不用传参 canvasId,直接传入canvas实例即可。
参考文档:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/wx.canvasToTempFilePath.html
改变下写法即可 参考下方示例

<template>  
    <view>  
        <button @tap="handleclick">canvas</button>  
        <image :src="imageSrc" mode="widthFix"></image>  
    </view>  
</template>  

<script setup>  
    import {  
        ref  
    } from 'vue'  
    const imageSrc = ref()  
    const handleclick = async () => {  
        // 创建离屏 2D canvas 实例  
        const canvas = wx.createOffscreenCanvas({  
            type: '2d',  
            width: 300,  
            height: 300  
        })  
        // 获取 context。注意这里必须要与创建时的 type 一致  
        const context = canvas.getContext('2d')  
        // 创建一个图片  
        const image = canvas.createImage()  
        // 等待图片加载  
        await new Promise(resolve => {  
            image.onload = resolve  
            image.src = "https://img-cdn-aliyun.dcloud.net.cn/guide/uniapp/app_download.png" // 要加载的图片 url  
        })  
        // 把图片画到离屏 canvas 上  
        context.clearRect(0, 0, 300, 300)  
        context.drawImage(image, 0, 0, 300, 300)  
        // 获取画完后的数据  
        uni.canvasToTempFilePath({  
            canvas: canvas,  
            success: (info) => {  
                imageSrc.value = info.tempFilePath  
            }  
        })  

    }  
</script>  

<style lang="scss">  

</style>

要回复问题请先登录注册