之前一直用的CanvasContext
,但是微信又双叒改规则了,在新版的基础库中不再支持,提供了一个Canvas
实例代替。
这个Canvas
实例需要用SelectorQuery
来获取,SelectorQuery
又需要wx.createSelectorQuery()
来获取。
官网文档这一点写的是真垃圾,一层套一层一点也不清晰(╬◣д◢)
代码+注释:
WXML代码:
<canvas type="2d" id="myCanvas" style="width:300px;height:300px;"></canvas>
获取创建实例:
wx.createSelectorQuery()
.select('#myCanvas')
.exec(res=>{
let ctx = res[0].node.getContext('2d');//getContext返回Canvas 的绘图上下文
});
//select:在当前页面下选择第一个匹配选择器 selector 的节点。返回一个 NodesRef 对象实例,可以用于获取节点信息,用法类似css选择器
//node(function callback):获取 Node 节点实例
//exec(function callback):执行所有的请求。请求结果按请求次序构成数组,在callback的第一个参数中返回
绘制例子
- 画方块
wx.createSelectorQuery()
.select('#myCanvas')
.fields({ node: true, size: true })
.exec(res=>{
let ctx = res[0].node.getContext('2d');//getContext返回Canvas 的绘图上下文
let canvas = res[0].node;
// 通过设备的像素比等重新绘制宽高
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
ctx.fillStyle='#FF0000';
ctx.fillRect(0,0,80,100);
})
2. 画文字
wx.createSelectorQuery()
.select('#myCanvas')
.fields({ node: true, size: true })
.exec(res=>{
let ctx = res[0].node.getContext('2d');//getContext返回Canvas 的绘图上下文
let canvas = res[0].node;
// 通过设备的像素比等重新绘制宽高
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
ctx.font="30px Arial";
ctx.fillText("Hello World",10,50);
})
3. 画图片
wx.createSelectorQuery()
.select('#myCanvas')
.fields({ node: true, size: true })
.exec(res=>{
let ctx = res[0].node.getContext('2d');//getContext返回Canvas 的绘图上下文
let canvas = res[0].node;
// 通过设备的像素比等重新绘制宽高
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
let image = canvas.createImage();//创建iamge实例
image.src = './car.png';
image.onload = function (rrr) {
ctx.drawImage(image, 20, 20, 50, 50);
}
})
其他的和HTML中的canvas相似
菜鸟教程-canvas