微信小程序 canvas 手寫簽名(2d)
canvas 2d 目前支持預覽,不支持真機調試
index.wxml
<canvas type="2d" id="canvas" bindtouchmove="move" bindtouchstart="start" binderror="error" style="width:{{width}}px;height:{{height}}px;"></canvas> <view class="btn"> <button bindtap="clearClick">重簽</button> <button bindtap="saveClick">完成簽名</button> </view>
index.wxss
page {
background-color: #e9f2f1;
}
.btn {
display: flex;
flex-direction: row;
justify-self: baseline;
margin: 15rpx;
}
.btn button:first-child {
color: #3fa89a;
}
.btn button:last-child {
color: white;
background-color: #3fa89a;
}
button {
width: 200rpx;
border-radius: 5rpx;
box-shadow: 0px 0px 1px 1px #c5c5c5;
}
canvas {
background-color: white;
}
index.json
{ "usingComponents": {}, "pageOrientation": "landscape", "navigationBarBackgroundColor":"#3fa89a", "navigationBarTextStyle":"white", "navigationBarTitleText":"手寫簽名" }
index.js
const app = getApp() Page({ data: { canvas: '', ctx: '', pr:0, width: 0, height: 0, first:true, }, start(e) { if(this.data.first){ this.clearClick(); this.setData({first:false}) } this.data.ctx.beginPath(); // 開始創建一個路徑,如果不調用該方法,最后無法清除畫布 this.data.ctx.moveTo(e.changedTouches[0].x, e.changedTouches[0].y) // 把路徑移動到畫布中的指定點,不創建線條。用 stroke 方法來畫線條 }, move(e) { this.data.ctx.lineTo(e.changedTouches[0].x, e.changedTouches[0].y) // 增加一個新點,然后創建一條從上次指定點到目標點的線。用 stroke 方法來畫線條 this.data.ctx.stroke() }, error: function (e) { console.log("畫布觸摸錯誤" + e); }, /** * 生命周期函數--監聽頁面加載 */ onLoad: function () { this.getSystemInfo() this.createCanvas() }, /** * 初始化 */ createCanvas() { const pr = this.data.pr; // 像素比 const query = wx.createSelectorQuery(); query.select('#canvas').fields({ node: true, size: true }).exec((res) => { const canvas = res[0].node; const ctx = canvas.getContext('2d'); canvas.width = this.data.width*pr; // 畫布寬度 canvas.height = this.data.height*pr; // 畫布高度 ctx.scale(pr,pr); // 縮放比 ctx.lineGap = 'round'; ctx.lineJoin = 'round'; ctx.lineWidth = 4; // 字體粗細 ctx.font = '40px Arial'; // 字體大小, ctx.fillStyle = '#ecf0ef'; // 填充顏色 ctx.fillText('簽名區', res[0].width / 2 - 60, res[0].height / 2) this.setData({ ctx, canvas }) }) }, // 獲取系統信息 getSystemInfo() { let that = this; wx.getSystemInfo({ success(res) { that.setData({ pr:res.pixelRatio, width: res.windowWidth, height: res.windowHeight - 75, }) } }) }, clearClick: function () { //清除畫布 this.data.ctx.clearRect(0, 0, this.data.width, this.data.height); }, //保存圖片 saveClick: function () { wx.canvasToTempFilePath({ x: 0, y: 0, width: this.data.width, height: this.data.height, destWidth:this.data.width*this.data.pr, destHeight: this.data.height*this.data.pr, canvasId: 'canvas', canvas: this.data.canvas, fileType: 'png', success(res) { wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success(res) { wx.showToast({ title: '保存成功', icon: 'success' }) } }) } }) } })
效果圖

簽名效果

PNG圖

哇!又賺了一天人民幣

浙公網安備 33010602011771號