主要用于绘制图像,在页面上放置一个就相当于在页面放置了一块画布,可以在其中进行图形绘制。组件是一块无色透明区域,本身没有绘制能力,它仅仅是容器,需要调用相关API来完成实际绘图任务,组件默认宽度300px,高度225px,统一页面中的canvas-id不能重复,如果使用一个已经出现过的canvas-id,该组件对应的画布将被隐藏不再正常工作,其属性如下:
属性 | 类型 | 默认值 | 必填 | 说明 | 最低版本 |
---|---|---|---|---|---|
canvas-id | string | 是 | canvas 组件的唯一标识符 | 1.0.0 | |
disable-scroll | boolean | false | 否 | 当在 canvas 中移动时且有绑定手势事件时,禁止屏幕滚动以及下拉刷新 | 1.0.0 |
bindtouchstart | eventhandle | 是 | 手指触摸动作开始 | 1.0.0 | |
bindtouchmove | eventhandle | 是 | 手指触摸后移动 | 1.0.0 | |
bindtouchend | eventhandle | 是 | 手指触摸动作结束 | 1.0.0 | |
bindtouchcancel | eventhandle | 是 | 手指触摸动作被打断,如来电提醒,弹窗 | 1.0.0 | |
bindlongtap | eventhandle | 是 | 手指长按 500ms 之后触发,触发了长按事件后进行移动不会触发屏幕的滚动 | 1.0.0 | |
binderror | eventhandle | 是 | 当发生错误时触发 error 事件,detail = {errMsg} | 1.0.0 |
简单示例代码如下:
Page({
onReady:function(){
//获取绘图上下文
var context = wx.createContext();
context.setStrokeStyle("#0000ff");//设置线条样式
context.setLineWidth(3);//设置线条宽度
context.rect(3,2,150,200);//添加一个矩阵
context.stroke();//对当前路径进行描边
//绘制图像
wx.drawCanvas({
canvasId:'myCanvas',
actions:context.getActions()
});
console.log('asdf');
}
})
执行结果如下:
进阶演示代码:
.canvas {
width: 305px;
height: 305px;
background-color: #fff;
}
Page({
onReady: function () {
this.position = {
x: 150,
y: 150,
vx: 2,
vy: 2
}
this.drawBall()
this.interval = setInterval(this.drawBall, 17)
},
drawBall: function () {
var p = this.position
p.x += p.vx
p.y += p.vy
if (p.x >= 300) {
p.vx = -2
}
if (p.x <= 7) {
p.vx = 2
}
if (p.y >= 300) {
p.vy = -2
}
if (p.y <= 7) {
p.vy = 2
}
var context = wx.createContext()
function ball(x, y) {
context.beginPath(0)
context.arc(x, y, 5, 0, Math.PI * 2)
context.setFillStyle('#1aad19')
context.setStrokeStyle('rgba(1,1,1,0)')
context.fill()
context.stroke()
}
ball(p.x, 150)
ball(150, p.y)
ball(300 - p.x, 150)
ball(150, 300 - p.y)
ball(p.x, p.y)
ball(300 - p.x, 300 - p.y)
ball(p.x, 300 - p.y)
ball(300 - p.x, p.y)
wx.drawCanvas({
canvasId: 'canvas',
actions: context.getActions()
})
},
onUnload: function () {
clearInterval(this.interval)
}
})
app.wxss
page {
background-color: #F8F8F8;
height: 100%;
font-size: 32rpx;
line-height: 1.6;
}
.page-body {
padding: 20rpx 0;
}
.page-body-wrapper {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
执行结果如下:
简单示例代码如下:
执行结果如下: