基础库 1.0.0 开始支持,低版本需做兼容处理。
画布。2.9.0 起支持一套新 Canvas 2D 接口(需指定 type 属性),同时支持同层渲染,原有接口不再维护。相关api:获取 canvas 实例。属性类型默认值必填说明最低版本typestring否指定 canvas 类型,支持 2d (2.9.0) 和 webgl (2.7.0)2.7.0
canvas-idstring否canvas 组件的唯一标识符,若指定了 type 则无需再指定该属性1.0.0
disable-scrollbooleanfalse否当在 canvas 中移动时且有绑定手势事件时,禁止屏幕滚动以及下拉刷新1.0.0
bindtouchstarteventhandle否手指触摸动作开始1.0.0
bindtouchmoveeventhandle否手指触摸后移动1.0.0
bindtouchendeventhandle否手指触摸动作结束1.0.0
bindtouchcanceleventhandle否手指触摸动作被打断,如来电提醒,弹窗1.0.0
bindlongtapeventhandle否手指长按 500ms 之后触发,触发了长按事件后进行移动不会触发屏幕的滚动1.0.0
binderroreventhandle否当发生错误时触发 error 事件,detail = {errMsg}1.0.0
Bug & Tiptip:canvas 标签默认宽度300px、高度150px
tip:同一页面中的 canvas-id 不可重复,如果使用一个已经出现过的 canvas-id,该 canvas 标签对应的画布将被隐藏并不再正常工作
tip:开发者工具中默认关闭了 GPU 硬件加速,可在开发者工具的设置中开启“硬件加速”提高 WebGL 的渲染性能
tip: WebGL 支持通过 getContext('webgl', { alpha: true }) 获取透明背景的画布
tip: Canvas 2D(新接口)需要显式设置画布宽高 (默认为 300x150)
bug: 避免设置过大的宽高,在安卓下会有crash的问题
Canvas 2D 示例代码
// canvas.js
Page({
onReady() {
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.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)
ctx.fillRect(0, 0, 100, 100)
})
}
})
WebGL 示例代码
// canvas.js
Page({
onReady() {
const query = wx.createSelectorQuery()
query.select('#myCanvas').node().exec((res) => {
const canvas = res[0].node
const gl = canvas.getContext('webgl')
gl.clearColor(1, 0, 1, 1)
gl.clear(gl.COLOR_BUFFER_BIT)
})
}
})
示例代码(旧的接口)
Page({
canvasIdErrorCallback: function (e) {
console.error(e.detail.errMsg)
},
onReady: function (e) {
// 使用 wx.createContext 获取绘图上下文 context
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()
}
})