微信小程序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初始化完成后再绘制即可.

相关推荐
说私域11 小时前
AI智能名片商城小程序数据清洗的持续运营策略与实践研究
大数据·人工智能·小程序·流量运营·私域运营
东东51611 小时前
xxx食堂移动预约点餐系统 (springboot+微信小程序)
spring boot·微信小程序·小程序·毕业设计·个人开发·毕设
CHU72903512 小时前
一番赏盲盒抽卡机小程序:解锁惊喜体验与社交乐趣的多元功能设计
前端·小程序·php
2501_9159184114 小时前
HTTPS 代理失效,启用双向认证(mTLS)的 iOS 应用网络怎么抓包调试
android·网络·ios·小程序·https·uni-app·iphone
数字游民952715 小时前
半年时间大概上了70个web站和小程序,累计提示词超过20w
人工智能·ai·小程序·vibecoding·数字游民9527
说私域15 小时前
微商企业未来迭代的核心方向与多元探索——以链动2+1模式AI智能名片商城小程序为核心支撑
大数据·人工智能·小程序·流量运营·私域运营
276695829216 小时前
美团 小程序 mtgsig
python·小程序·node·js·mtgsig1.2·美团小程序·大众点评小程序
2501_9151063216 小时前
混合应用(Hybrid)安全加固,不依赖源码对成品 IPA 混淆
android·安全·小程序·https·uni-app·iphone·webview
00后程序员张17 小时前
无需越狱,来对 iOS 设备进行调试、管理与分析
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张17 小时前
在 iOS 上架中如何批量方便快捷管理 Bundle ID
android·ios·小程序·https·uni-app·iphone·webview