微信小程序?qū)崿F(xiàn)簽字功能
效果展示
準(zhǔn)備工作
主要用到了 bindtouchstart , bindtouchmove 兩個屬性,捕捉手指移動的同時,將移動前的坐標(biāo)和移動后的坐標(biāo)用canvas的畫圖api繪制出來
這個api用于創(chuàng)建并獲取指定canvas對象
代碼說明
在wxml中聲明一個canvas
指定canvas-id和觸摸開始和移動函數(shù)
<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() },
給手指觸摸綁定函數(shù)
// 開始觸摸 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 style="margin: 0 15rpx;width: 720rpx;height: 720rpx;border: 1px #333 solid;background-color: #fff;" 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 style="width:360rpx;height:360rpx;margin: 10rpx 0;" 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(); }, /**導(dǎo)出圖片 */ 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: '導(dǎo)出失敗', icon: 'none', duration: 2000 }) } })) }, onShow: function() { const context = wx.createCanvasContext('firstCanvas') this.setData({ context: context }) context.draw() }, })
總結(jié)
以上所述是小編給大家介紹的微信小程序?qū)崿F(xiàn)簽字功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
js獲取時間并實現(xiàn)字符串和時間戳之間的轉(zhuǎn)換
這篇文章主要介紹了js獲取時間并實現(xiàn)字符串和時間戳之間的轉(zhuǎn)換,需要的朋友可以參考下2015-01-01實用又漂亮的BootstrapValidator表單驗證插件
這篇文章主要為大家詳細(xì)介紹了好用又漂亮的BootstrapValidator表單驗證插件,感興趣的小伙伴們可以參考一下2016-05-05JavaScript結(jié)合Bootstrap仿微信后臺多圖文界面管理
這篇文章主要為大家詳細(xì)介紹了js結(jié)合Bootstrap仿微信后臺多圖文界面管理,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-07-07