在微信小程序中,同樣支持canvas的使用碟渺。
1.首先在 wxml 頁(yè)面中添加<canvas></canvas>組件:
<canvas class="sign" canvas-id="sign" bindtouchmove="move" bindtouchstart="start" bindtouchend="end" bindtouchcancel="cancel" bindlongtap="tap" disable-scroll="true" binderror="error">
</canvas>
2.在小程序的 js 中初始化所需的變量如下:
// 初始化簽名變量,放在 Page 前
var content = null;
var touchs = [];
//頁(yè)面的data數(shù)據(jù)突诬,在 Page 中
data: {
imgList:[],
signImage: ''
}
3.在小程序的 js 中 Page 內(nèi)寫入如下函數(shù):
// 畫布的觸摸移動(dòng)開始手勢(shì)響應(yīng)
start: function (event) {
// console.log("觸摸開始" + event.changedTouches[0].x);
// console.log("觸摸開始" + event.changedTouches[0].y);
//獲取觸摸開始的 x,y
let point = { x: event.changedTouches[0].x, y: event.changedTouches[0].y }
touchs.push(point);
},
// 畫布的觸摸移動(dòng)手勢(shì)響應(yīng)
move: function (e) {
let point = { x: e.touches[0].x, y: e.touches[0].y }
touchs.push(point);
if (touchs.length >= 2) {
this.draw(touchs);
}
},
// 畫布的觸摸移動(dòng)結(jié)束手勢(shì)響應(yīng)
end: function (e) {
console.log("觸摸結(jié)束" + e);
//清空軌跡數(shù)組
for (let i = 0; i < touchs.length; i++) {
touchs.pop();
}
},
// 畫布的觸摸取消響應(yīng)
cancel: function (e) {
console.log("觸摸取消" + e);
},
// 畫布的長(zhǎng)按手勢(shì)響應(yīng)
tap: function (e) {
console.log("長(zhǎng)按手勢(shì)" + e);
},
error: function (e) {
console.log("畫布觸摸錯(cuò)誤" + e);
},
/**
* 生命周期函數(shù)--監(jiān)聽頁(yè)面加載
*/
onLoad: function (options) {
//獲得Canvas的上下文
content = wx.createCanvasContext('sign');
//設(shè)置線的顏色
content.setStrokeStyle("#000");
//設(shè)置線的寬度
content.setLineWidth(3);
//設(shè)置線兩端端點(diǎn)樣式更加圓潤(rùn)
content.setLineCap('round');
//設(shè)置兩條線連接處更加圓潤(rùn)
content.setLineJoin('round');
},
//繪制
draw: function (touchs) {
let point1 = touchs[0];
let point2 = touchs[1];
touchs.shift();
content.moveTo(point1.x, point1.y);
content.lineTo(point2.x, point2.y);
content.stroke();
content.draw(true);
},
//清除操作
clearClick: function () {
//清除畫布
content.clearRect(0, 0,750, 700);
content.draw(true);
},
//保存圖片
saveClick: function () {
var that = this;
wx.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: function (res) {
//打印圖片路徑
console.log(res.tempFilePath);
//設(shè)置保存的圖片
that.setData({
signImage: res.tempFilePath
})
}
})
}