官方文档canvas:https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html
调试基础库:2.9.3
一开始,我使用的是官方文档里的示例代码进行修改的,即
// js methods内
drawOn:function(){
var context = wx.createCanvasContext('firstCanvas')
context.setStrokeStyle("#00ff00")
context.setLineWidth(5)
context.rect(0, 0, 200, 200)
context.stroke()
context.setStrokeStyle("#ff0000")
context.setLineWidth(2)
context.moveTo(160, 100)
context.arc(100, 100, 60, 0, 2 * Math.PI, true)
context.moveTo(140, 100)
context.arc(100, 100, 40, 0, Math.PI, false)
context.moveTo(85, 80)
context.arc(80, 80, 5, 0, 2 * Math.PI, true)
context.moveTo(125, 80)
context.arc(120, 80, 5, 0, 2 * Math.PI, true)
context.stroke()
context.draw()
}
发现这个方法无效, wxml略,后查阅官方文档发现component只支持class选择器,是不是不支持canvas-id ?即不支持wx.createCanvasContext(),后换了Canvas 2D的示例代码才成功,如下
/*
请插入js methods 里
*/
drawOn:function(){
var query = this.createSelectorQuery()
/*
component只支持class索引选择,见
https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
*/
query.select('.first-canvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
/* 下面添加canvas 2D代码 */
ctx.fillRect(0, 0, 100, 100)
})
}
另:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/RenderingContext.html