1、canvas標簽(touchstart、touchmove、touchend)
<canvas @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
<view @click="clear">清除</view>
<view @click="finish">完成</view>
2、uniapp中使用
onLoad() {
this.ctx = uni.createCanvasContext("mycanvas", this); // 創建繪圖對象
// 設置畫筆樣式
this.ctx.lineWidth = 4;
this.ctx.lineCap = "round";
this.ctx.lineJoin = "round";
},
methods:{
// 觸摸開始,獲取到起點
touchstart:function(e) {
let startX = e.changedTouches[0].x;
let startY = e.changedTouches[0].y;
let startPoint = { X:startX,Y:startY };
// 由于uni對canvas的實現有所不同,這里需要把起點存起來
this.points.push(startPoint);
// 每次觸摸開始,開啟新的路徑
this.ctx.beginPath();
},
// 觸摸移動,獲取到路徑點
touchmove:function(e) {
let moveX = e.changedTouches[0].x;
let moveY = e.changedTouches[0].y;
let movePoint = {X:moveX,Y:moveY};
this.points.push(movePoint); // 存點
let len = this.points.length;
if (len >= 2) {
this.draw(); // 繪制路徑
}
},
// 觸摸結束,將未繪制的點清空防止對后續路徑產生干擾
touchend:function() {
this.points = [];
},
/*
繪制筆跡:
1.為保證筆跡實時顯示,必須在移動的同時繪制筆跡
2.為保證筆跡連續,每次從路徑集合中區兩個點作為起點(moveTo)和終點(lineTo)
3.將上一次的終點作為下一次繪制的起點(即清除第一個點)
*/
draw: function() {
let point1 = this.points[0];
let point2 = this.points[1];
this.points.shift();
this.ctx.moveTo(point1.X, point1.Y);
this.ctx.lineTo(point2.X, point2.Y);
this.ctx.stroke();
this.ctx.draw(true);
},
// 清空畫布
clear:function() {
let that = this;
uni.getSystemInfo({
success: function(res) {
let canvasw = res.windowWidth;
let canvash = res.windowHeight;
that.ctx.clearRect(0, 0, canvasw, canvash);
that.ctx.draw(true);
},
})
},
// base64轉成blob對象
dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n); // 8位無符號整數,長度1個字節
console.log(mime)
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// console.log(JSON.stringify(u8arr));
return new Blob([u8arr], {
type: mime
});
},
// 完成繪畫并上傳圖片
finish:function() {
var that = this;
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
success: function(res) {
let path = res.tempFilePath;
console.log(path, that.dataURLtoBlob(path));
}
})
}
}