今天关于微信小程序的画布,做了个简单的范例,大家来看看吧
wxml的代码
<canvas style="width: 300px; height: 200px;" canvas-id="fourCanvas" bindtouchstart="start" bindtap="click" >画布效果</canvas>
js代码
Page({
data:{
canvaid:'fourCanvas',
num:'1'
},
canvasIdErrorCallback: function (e) {
console.error(e.detail.errMsg)
},
click:function(){
var nums=this.data.num;
nums++;
if(nums%2==0){
var context = wx.createContext()
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()
}else{
var context = wx.createContext()
context.setStrokeStyle("#00ff00")
context.setLineWidth(5)
context.rect(0, 0, 200, 200)
context.stroke()
context.setStrokeStyle("#ff0000")
context.setLineWidth(2)
context.moveTo(160, 103)
context.arc(100, 100, 60, 0, 2 * Math.PI, true)
context.moveTo(59, 137)
context.arc(100, 135, 40, 3.2, Math.PI, false)
context.moveTo(84, 83)
context.arc(80, 80, 5, 0, 2 * Math.PI, true)
context.moveTo(124, 79)
context.arc(120, 80, 5, 0, 2 * Math.PI, true)
context.stroke()
}
wx.drawCanvas({
canvasId: this.data.canvaid,
actions: context.getActions()
})
this.setData({
num:nums
})
},
onReady: function (e) {
var context = wx.createContext()
context.setStrokeStyle("#00ff00")
context.setLineWidth(5)
context.rect(0, 0, 200, 200)
context.stroke()
context.setStrokeStyle("#ff0000")
context.setLineWidth(2)
context.moveTo(160, 103)
context.arc(100, 100, 60, 0, 2 * Math.PI, true)
context.moveTo(59, 137)
context.arc(100, 135, 40, 3.2, Math.PI, false)
context.moveTo(84, 83)
context.arc(80, 80, 5, 0, 2 * Math.PI, true)
context.moveTo(124, 79)
context.arc(120, 80, 5, 0, 2 * Math.PI, true)
context.stroke()
wx.drawCanvas({
canvasId: this.data.canvaid,
actions: context.getActions()
})
}
})
这个对小程序的小白来说,也是很简单的,接下来给大家发效果图吧!
点击后的效果图(可以重复 无限次数的点击哦)
若有不懂的地方,可以在下方评论,也可以扫描下方二维码进行讨论