微信小程序canvas开发的一些坑和总结-持续更新

一,新版的canvas和旧版不同,需要增加type=2d,且初始化不一样

第一步是html中修改

c 复制代码
<canvas canvas-id="myCanvas" />
<!-- 修改为以下 -->
<canvas id="myCanvas" type="2d" />

第二步是初始化变了

c 复制代码
const context = wx.createCanvasContext('myCanvas')
//
// 修改为以下
//
wx.createSelectorQuery()
    .select('#myCanvas') // 在 WXML 中填入的 id
    .node(({ node: canvas }) => {
        const context = canvas.getContext('2d')
    })
    .exec()

二,在popup弹窗中使用canvas绘制无效

当canvas重新渲染时,canvas中的内容全部都会被清空。 解决 popup弹出后,不要马上绘制,需要等待popup中的canvas渲染完成后,在调用canvas取绘制就好了!

这是因为新版的canvas绘制是同步的,而canvas的初始化又是异步的,这就导致popup弹窗我们用v-if来创建时,就会发生这个问题.

我的修改:

c 复制代码
showCanvas(){
	this.imgShow=true
	const that=this
	that.$nextTick(()=>{
		// 使用 fabric 绑定画布
		wx.createSelectorQuery()
		    .select('#poster-canvas') // 在 WXML 中填入的 id
		    .fields({ node: true, size: true })
		    .exec((res) => {
		        // Canvas 对象
				const canvasNode = res[0].node
		        // 渲染上下文
				that.context = canvasNode.getContext('2d')
				const dpr = wx.getSystemInfoSync().pixelRatio
				canvasNode.width = res[0].width * dpr
			    canvasNode.height = res[0].height * dpr
			    that.context.scale(dpr, dpr)
				that.context.clearRect(0, 0, that.context.canvas.width, that.context.canvas.height)
				const image = canvasNode.createImage()
				image.src = 'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_wx_logo.png'
				image.onload = () => {
					console.log("图片加载完成",that.context)
				    that.context.drawImage(
				        image,
				        0,
				        0,
				        150,
				        100,
				    )
					that.context.fillStyle="red"
					that.context.strokeStyle="blue"
					that.context.beginPath()
					that.context.moveTo(10,10)
					that.context.lineTo(60, 10)
					that.context.lineTo(60, 40)
					that.context.closePath()
					that.context.stroke()
					that.context.fill()
					// 这里绘制完成
					console.log('draw done')
				}
				
		})
	})
	
},

也就是放置在nextTick中,等canvas初始化完成后再绘制即可.

相关推荐
汤姆yu1 天前
基于微信小程序的特色农产品交易系统
微信小程序·小程序
毕设源码-赖学姐1 天前
【开题答辩全过程】以 赣农乐微信小程序为例,包含答辩的问题和答案
微信小程序·小程序
一 乐1 天前
远程在线诊疗|在线诊疗|基于java和小程序的在线诊疗系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·小程序
2501_915918411 天前
HTTP和HTTPS工作原理、安全漏洞及防护措施全面解析
android·http·ios·小程序·https·uni-app·iphone
2501_916007471 天前
如何在 Windows 电脑上调试 iOS 设备上的 Safari?完整方案与实战经验分享
android·windows·ios·小程序·uni-app·iphone·safari
2501_915918411 天前
uni-app iOS日志管理实战,从调试控制台到系统日志的全链路采集与分析指南
android·ios·小程序·https·uni-app·iphone·webview
毕设源码-钟学长1 天前
【开题答辩全过程】以 二手小型电子产品商城小程序为例,包含答辩的问题和答案
小程序
hdsoft_huge1 天前
小程序弱网 / 无网场景下 CacheManager 离线表单与拍照上传解决方案
java·小程序·uni-app
Jerry2505091 天前
微信小程序必要要安装SSL证书吗?小程序SSL详解
网络·网络协议·网络安全·微信小程序·小程序·https·ssl
WKK_1 天前
uniapp小程序 订阅消息推送
小程序·uni-app