本文是在微信小程序中使用 canvas 2d 來(lái)實(shí)現(xiàn)簽字板功能;
效果圖:
代碼:
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文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-700796.html
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)
},
//觸摸移動(dòng)
move (e) {
this.data.ctx.lineTo(e.touches[0].x, e.touches[0].y)
this.data.ctx.stroke()//將上下文繪制到canvas中
},
//觸摸結(jié)束
end (e) {
this.data.ctx.closePath()
},
//清除畫布內(nèi)容
clear(){
this.data.ctx.clearRect(0, 0,this.data.canvas.width, this.data.canvas.height)
this.setData({
canvanImg:""
})
},
//點(diǎn)擊保存生成圖片
save(){
this.setData({
canvanImg:this.data.canvas.toDataURL("image/png")
})
},
}
})
3、總結(jié)
canvas 的寬度和高度可以寫死,也可以根據(jù)當(dāng)前可是區(qū)域動(dòng)態(tài)計(jì)算;需要注意的是 res[0].node 的寬度和高度的計(jì)算是當(dāng)前 canvas 元素上的寬度和高度乘設(shè)備的 pixelRatio ;文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-700796.html
到了這里,關(guān)于微信小程序使用 canvas 2d 實(shí)現(xiàn)簽字板組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!