uniapp的pc/移动手写签名
小编辛苦了一上午,话不多,直接上代码
<template>
<!-- 签名 -->
<view class="cu-modal" >
<view class="cu-dialog">
<view class="padding-xl">
<text>签名区域:</text>
<canvas class="mycanvas" @mousedown="cli1" @mousemove="cli2" @mouseup="cli3" disable-scroll="true" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
<!-- 底部操作按钮 -->
<view class="footer">
<view class="left" @click="finish">确定签名</view>
<view class="right" @click="clear">重新签名</view>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
var tempPoint = [];
export default {
data() {
return {
isShow:false,
//绘图图像
ctx: '',
//路径点集合
points: [],
isDrawing:false
}
},
created() {
this.ctx = uni.createCanvasContext('mycanvas', this);
//设置画笔样式
this.ctx.lineWidth = 2;
this.ctx.lineCap = 'round';
this.ctx.lineJoin = 'round';
},
methods:{
// 鼠标按下
cli1(e){
let elm = this.$el.querySelector('.mycanvas')
var x = e.pageX - elm.offsetLeft;
var y = e.pageY - elm.offsetTop;
this.isDrawing=true
let startX = x;
let startY = y;
let startPoint = { X: startX, Y: startY };
this.points.push(startPoint);
//每次触摸开始,开启新的路径
this.ctx.beginPath();
},
// 鼠标移动
cli2(e){
if(this.isDrawing==true){
let elm = this.$el.querySelector('.mycanvas')
var x = e.pageX - elm.offsetLeft;
var y = e.pageY - elm.offsetTop;
let moveX =x;
let moveY = y;
let movePoint = { X: moveX, Y: moveY };
this.points.push(movePoint); //存点
let len = this.points.length;
if (len >= 2) {
this.draw(); //绘制路径
}
tempPoint.push(movePoint);
}
},
// 鼠标弹起
cli3(e){
this.isDrawing=false
this.points = [];
},
touchstart(e) {
console.log(e)
console.log(e.changedTouches)
let startX = e.changedTouches[0].x;
let startY = e.changedTouches[0].y;
let startPoint = { X: startX, Y: startY };
this.points.push(startPoint);
//每次触摸开始,开启新的路径
this.ctx.beginPath();
},
touchmove(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(); //绘制路径
}
tempPoint.push(movePoint);
},
touchend() {
this.points = [];
},
draw() {
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() {
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);
}
});
},
finish() {
let that = this;
if (tempPoint.length == 0) {
// uni.showToast({
// title: '请先签名',
// icon: 'none',
// duration: 2000
// });
alert('未签名')
return;
}
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
success: function(res) {
//这里的res.tempFilePath就是生成的签字图片
console.log(res.tempFilePath);
}
});
},
}
}
</script>
<style>
.mycanvas{
width: 100vw;
border: 1px solid black;
}
</style>