1、canvas標(biāo)簽(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); // 創(chuàng)建繪圖對(duì)象
// 設(shè)置畫(huà)筆樣式
this.ctx.lineWidth = 4;
this.ctx.lineCap = "round";
this.ctx.lineJoin = "round";
},
methods:{
// 觸摸開(kāi)始,獲取到起點(diǎn)
touchstart:function(e) {
let startX = e.changedTouches[0].x;
let startY = e.changedTouches[0].y;
let startPoint = { X:startX,Y:startY };
// 由于uni對(duì)canvas的實(shí)現(xiàn)有所不同,這里需要把起點(diǎn)存起來(lái)
this.points.push(startPoint);
// 每次觸摸開(kāi)始,開(kāi)啟新的路徑
this.ctx.beginPath();
},
// 觸摸移動(dòng),獲取到路徑點(diǎn)
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); // 存點(diǎn)
let len = this.points.length;
if (len >= 2) {
this.draw(); // 繪制路徑
}
},
// 觸摸結(jié)束,將未繪制的點(diǎn)清空防止對(duì)后續(xù)路徑產(chǎn)生干擾
touchend:function() {
this.points = [];
},
/*
繪制筆跡:
1.為保證筆跡實(shí)時(shí)顯示,必須在移動(dòng)的同時(shí)繪制筆跡
2.為保證筆跡連續(xù),每次從路徑集合中區(qū)兩個(gè)點(diǎn)作為起點(diǎn)(moveTo)和終點(diǎn)(lineTo)
3.將上一次的終點(diǎn)作為下一次繪制的起點(diǎn)(即清除第一個(gè)點(diǎn))
*/
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);
},
// 清空畫(huà)布
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轉(zhuǎn)成blob對(duì)象
dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n); // 8位無(wú)符號(hào)整數(shù),長(zhǎng)度1個(gè)字節(jié)
console.log(mime)
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// console.log(JSON.stringify(u8arr));
return new Blob([u8arr], {
type: mime
});
},
// 完成繪畫(huà)并上傳圖片
finish:function() {
var that = this;
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
success: function(res) {
let path = res.tempFilePath;
console.log(path, that.dataURLtoBlob(path));
}
})
}
}