本文是在微信小程序中使用 canvas 2d 来实现签字板功能;
效果图:
代码:
1、wxml
<view>
<canvas
id="canvas"
type="2d"
bindtouchstart="start"
bindtouchmove="move"
bindtouchend="end"
style="border: 1px solid #ccc; width:100%; height:800rpx"
></canvas>
<view style="display: flex;">
<button bindtap="clear">清除</button>
<button bindtap="save">保存</button>
</view>
<image src="{{canvanImg}}"></image>
</view>
2、js
Component({
properties: {
},
data: {
canvas:null,
canvanImg:"",
ctx:null
},
lifetimes:{
ready(){
let that = this;
wx.createSelectorQuery().in(this)
.select("#canvas")
.fields({
node:true,
size:true
}).exec((res)=>{
let canvas = res[0].node;
let ctx = canvas.getContext("2d");
let dpr = wx.getSystemInfoSync().pixelRatio;
canvas.width = res[0].width * dpr;
canvas.height = res[0].height * dpr;
ctx.fillStyle = "#fff";
// 利用阴影,消除锯齿
ctx.shadowBlur = 1;
ctx.shadowColor = '#000';
ctx.scale(dpr, dpr)
that.setData({
canvas,
ctx
})
})
}
},
methods: {
//触摸开始
start (e) {
this.data.ctx.beginPath()
this.data.ctx.moveTo(e.touches[0].x,e.touches[0].y)
},
//触摸移动
move (e) {
this.data.ctx.lineTo(e.touches[0].x, e.touches[0].y)
this.data.ctx.stroke()//将上下文绘制到canvas中
},
//触摸结束
end (e) {
this.data.ctx.closePath()
},
//清除画布内容
clear(){
this.data.ctx.clearRect(0, 0,this.data.canvas.width, this.data.canvas.height)
this.setData({
canvanImg:""
})
},
//点击保存生成图片
save(){
this.setData({
canvanImg:this.data.canvas.toDataURL("image/png")
})
},
}
})
3、总结
canvas 的宽度和高度可以写死,也可以根据当前可是区域动态计算;需要注意的是 res[0].node 的宽度和高度的计算是当前 canvas 元素上的宽度和高度乘设备的 pixelRatio ;