uni-app app端nvue页面中使用canvas ctx.draw回调函数没有触发

uni-app app端nvue页面中使用canvas ctx.draw回调函数没有触发

开发环境 版本号 项目创建方式
Mac 12.7.1 HBuilderX

产品分类:uniapp/App

PC开发环境操作系统:Mac

HBuilderX类型:正式

HBuilderX版本号:4.45

手机系统:Android

手机系统版本号:Android 12

手机厂商:荣耀

手机机型:Play7T

页面类型:nvue

vue版本:vue2

打包方式:云端

项目创建方式:HBuilderX


示例代码:

this.$nextTick(() => {
const ctx = uni.createCanvasContext("screenshotCanvas");
ctx.fillStyle = '#007aff';
// 绘制一个矩形,参数分别为:左上角x坐标, 左上角y坐标, 宽度, 高度
ctx.fillRect(0, 0, 200, 100);
ctx.save();
ctx.fillStyle  = '#000000';
ctx.fillText('测试数据', 100, 50);
ctx.stroke();
console.log("ctx---", ctx);
// 在try中页不报错
try {
/**
  * 两种方式  
  * ctx.draw 在页面中都没有效果
  */
// 这里没有回调
ctx.draw(true, () => {
// 到这里的代码就没有触发了
console.log("ctx---", ctx);
setTimeout(() => {
console.log("ctx===", ctx);
}, 50)
})
/**
  * 下面这段draw的回调函数是触发了,但是uni.canvasToTempFilePath又没有触发 
  * 应该是上一步draw,没有绘制成功。
  */
// ctx.draw(true, (() => {
//  console.log("res---", res);
//  setTimeout(() => {
//      uni.canvasToTempFilePath({
//          canvasId: "screenshotCanvas",
//          fileType: 'png',
//          success: (res) => {
//            console.log('成功:', res.tempFilePath);
//          },
//          fail: (err) => {
//            console.error('失败:', err); // 输出具体错误信息
//          },
//          complete: () => {
//            console.log('调用完成'); // 确认 API 是否被触发
//          }
//      })
//  }, 50)
// })());
}catch(eror){
console.log("eror---", eror)
}

更多关于uni-app app端nvue页面中使用canvas ctx.draw回调函数没有触发的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app app端nvue页面中使用canvas ctx.draw回调函数没有触发的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在nvue页面中使用canvas时,确实存在一些特殊注意事项:

  1. 关于draw回调不触发的问题,这是nvue环境下的已知限制。nvue的canvas实现与vue页面有所不同,部分API的回调支持不完全。

  2. 解决方案建议:

  • 直接使用draw()不带回调的方式,通过setTimeout延迟后续操作
  • 改用weex的canvas模块(需引入dom模块)

修正后的代码示例:

this.$nextTick(() => {
  const ctx = uni.createCanvasContext("screenshotCanvas");
  ctx.fillStyle = '#007aff';
  ctx.fillRect(0, 0, 200, 100);
  ctx.save();
  ctx.fillStyle = '#000000';
  ctx.fillText('测试数据', 100, 50);
  ctx.stroke();
  
  // 直接调用draw不等待回调
  ctx.draw(true);
  
  // 延迟执行后续操作
  setTimeout(() => {
    uni.canvasToTempFilePath({
      canvasId: "screenshotCanvas",
      success: (res) => {
        console.log('成功:', res.tempFilePath);
      }
    });
  }, 100);
});
回到顶部