這篇文章給大家分享的是有關微信小程序如何實現簽字功能的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
效果展示
準備工作
1.canvas的使用
主要用到了 bindtouchstart , bindtouchmove 兩個屬性,捕捉手指移動的同時,將移動前的坐標和移動后的坐標用canvas的畫圖api繪制出來
2.wx.createCanvasContext
這個api用于創建并獲取指定canvas對象
代碼說明
在wxml中聲明一個canvas
指定canvas-id和觸摸開始和移動函數
<canvas canvas-id="firstCanvas" id='firstCanvas' bindtouchstart="bindtouchstart" bindtouchmove="bindtouchmove"></canvas>
初始化canvas
onShow: function() {
const context = wx.createCanvasContext('firstCanvas')
this.setData({
context: context
})
context.draw()
},給手指觸摸綁定函數
// 開始觸摸
bindtouchstart: function(e) {
console.log("bindtouchstart", e);
this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y)
},
// 觸摸移動
bindtouchmove: function(e) {
console.log("bindtouchstart", e);
this.data.context.lineTo(e.changedTouches[0].x, e.changedTouches[0].y);
this.data.context.stroke();
this.data.context.draw(true);
this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
},具體代碼
index.wxml
<view class="container">
<canvas canvas-id="firstCanvas" id='firstCanvas' bindtouchstart="bindtouchstart" bindtouchmove="bindtouchmove"></canvas>
<view class="btn">
<view bindtap='clear' class="clear">
清除
</view>
<view bindtap='export' class="submit">
提交
</view>
</view>
<image mode="aspectFill" src="{{imgUrl}}"></image>
</view>index.js
Page({
data: {
context: null,
imgUrl: ""
},
/**記錄開始點 */
bindtouchstart: function(e) {
this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y)
},
/**記錄移動點,刷新繪制 */
bindtouchmove: function(e) {
this.data.context.lineTo(e.changedTouches[0].x, e.changedTouches[0].y);
this.data.context.stroke();
this.data.context.draw(true);
this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
},
/**清空畫布 */
clear: function() {
this.data.context.draw();
},
/**導出圖片 */
export: function() {
const that = this;
this.data.context.draw(false, wx.canvasToTempFilePath({
x: 0,
y: 0,
fileType: 'jpg',
canvasId: 'firstCanvas',
success(res) {
const {
tempFilePath
} = res;
that.setData({
imgUrl: tempFilePath,
})
},
fail() {
wx.showToast({
title: '導出失敗',
icon: 'none',
duration: 2000
})
}
}))
},
onShow: function() {
const context = wx.createCanvasContext('firstCanvas')
this.setData({
context: context
})
context.draw()
},
})感謝各位的閱讀!關于“微信小程序如何實現簽字功能”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。