使用uni-app唯一id的canvas一直报canvas-id xx in this page has already existed

使用uni-app唯一id的canvas一直报canvas-id xx in this page has already existed

开发环境 版本号 项目创建方式
Windows 11 专业版 24H2 HBuilderX

产品分类:uniapp/小程序/微信


这是部分canvas组件代码:

<template>  
<view>  
<!-- 显示处理后的图片 -->  
<image v-if="processedImage" :src="processedImage" mode="widthFix" v-show="isShow"  
style="{width:cssWidth+'px',height:cssHeight+'px',...customStyle}" />  
<!-- 隐藏的Canvas -->  
<canvas :canvas-id="canvasName" [@error](/user/error)="canvasIdErrorCallback" :style="{  
        width: `${realWidth}px`,  
        height: `${realHeight}px`,  
        position: 'absolute',  
        left: '-9999px',  
        top: '-9999px'  
      }"></canvas>  
</view>  
</template>  

更多关于使用uni-app唯一id的canvas一直报canvas-id xx in this page has already existed的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

旧版canvas有问题,整套换成type="2d"的格式就正常了!

更多关于使用uni-app唯一id的canvas一直报canvas-id xx in this page has already existed的实战教程也可以访问 https://www.itying.com/category-93-b0.html


这个错误是因为在uni-app中,canvas-id在同一页面必须是唯一的。即使你使用了动态绑定的canvasName变量,如果这个变量在组件复用或页面重渲染时没有生成足够唯一的ID,就会报这个错误。

解决方法:

  1. 确保canvasName是真正唯一的,可以使用时间戳或随机数生成:
data() {
  return {
    canvasName: 'canvas_' + Date.now() + Math.random().toString(36).substr(2)
  }
}
  1. 如果canvas是动态生成的,在组件销毁时要确保清理canvas:
beforeDestroy() {
  // 小程序环境下需要手动销毁canvas
  if(process.env.UNI_PLATFORM === 'mp-weixin') {
    const ctx = uni.createCanvasContext(this.canvasName, this)
    ctx.draw()
  }
}
回到顶部