uni-app createCanvasContext在微信小程序中不兼容

uni-app createCanvasContext在微信小程序中不兼容

开发环境 版本号 项目创建方式
Windows 10 HBuilderX

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


<template>
<view class="goodsposter">
<view class="goodsposter_cen">
<view class="goodsposter_cen_t">
<canvas canvasId="goodsci" id="goodsci" type="2d" [@error](/user/error)="canvasIdErrorCallback"></canvas>
</view>
<view class="goodsposter_cen_b">
<view class="goodsposter_cen_b_i" [@click](/user/click)="onDownloadPoster">
下载海报
</view>
<view class="goodsposter_cen_b_i">
分享海报
</view>
</view>
</view>
</view>
</template>

<script setup>
import { onMounted, ref, reactive, defineProps, getCurrentInstance, nextTick } from 'vue'
const {proxy} = getCurrentInstance()  

const props = defineProps({
info: {
type: Object
}
})
onMounted(()=>{
let ctx = uni.createCanvasContext("goodsci",proxy)
console.log("这是canvas",ctx)
ctx.setFillStyle('red')
ctx.fillRect(10, 10, 150, 75)
ctx.draw()
})

const onDownloadPoster=()=>{
}

const canvasIdErrorCallback=(e)=>{
console.error(e.detail.errMsg)
}
</script>

<style scoped lang="scss">
.goodsposter {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 100;

&_cen {  
position: absolute;  
top: 50%;  
left: 50%;  
transform: translate(-50%, -50%);  
width: 80%;  
background-color: #fff;  
border-radius: 10rpx;  

&_t {  
padding: 20rpx;  
text-align: center;  

// canvas {  
//  width: 100%;  
//  height: auto;  
// }  
}  

&_b {  
display: flex;  
justify-content: space-around;  
padding: 20rpx;  

&_i {  
flex-grow: 1;  
text-align: center;  
color: $text-act-color;  
}  
}  
}
</style>

更多关于uni-app createCanvasContext在微信小程序中不兼容的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

uni 上的方法在微信上就是使用对应的微信方法,如果有问题请参照这个解决方法

更多关于uni-app createCanvasContext在微信小程序中不兼容的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在微信小程序中使用uni.createCanvasContext时,如果canvas的type设置为"2d",确实会出现兼容性问题。这是因为微信小程序的2D Canvas上下文创建方式与旧版Canvas不同。

解决方案:

  1. 将canvas的type属性移除或改为"webgl",使用旧版Canvas API
  2. 如果必须使用2D Canvas,需要改用微信小程序的专用API:
// 对于2D Canvas,应该这样创建上下文
const query = uni.createSelectorQuery().in(proxy)
query.select('#goodsci').node((res) => {
  const canvas = res.node
  const ctx = canvas.getContext('2d')
  // 然后使用标准的Canvas 2D API
  ctx.fillStyle = 'red'
  ctx.fillRect(10, 10, 150, 75)
}).exec()
回到顶部