<template>
<view>
<!-- canvas -->
<canvas class="mycanvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
<!-- 操作按钮 -->
<view class="footer">
<view class="footer-btn">
<u-button type="error" text="重签" @click="clear" plain></u-button>
</view>
<view class="footer-btn">
<u-button type="primary" text="保存" @click="finish"></u-button>
</view>
</view>
<image :src="SignatureImg" mode="widthFix"></image>
</view>
</template>
<script>
export default {
props:{
lineWidth:{
type:[Number,String],
default:4
}
},
data() {
return {
//绘图图像
ctx: '',
//路径点集合
points: [],
//签名图片
SignatureImg: ''
}
},
created() {
this.createCanvas()
},
methods: {
createCanvas() {
//创建绘图对象
this.ctx = uni.createCanvasContext('mycanvas', this);
//设置画笔样式
this.ctx.lineWidth = this.lineWidth;
this.ctx.lineCap = 'round';
this.ctx.lineJoin = 'round';
},
touchstart(e) {
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(); //绘制路径
}
},
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() {
uni.getSystemInfo({
success: (res) => {
let canvasw = res.windowWidth;
let canvash = res.windowHeight;
this.ctx.clearRect(0, 0, canvasw, canvash);
this.ctx.draw(true);
}
});
},
finish() {
let that = this;
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
success: (res) => {
//这里的res.tempFilePath就是生成的签字图片
this.SignatureImg=res.tempFilePath;
this.$u.toast("签字成功啦")
}
});
}
}
}
</script>
<style lang="scss" scoped>
uni-canvas {
width: 100%;
background-color: #F8F8F8;
}
.createCanvas {
width: 100%;
}
.footer {
margin-top: 32rpx;
display: flex;
align-items: center;
width: calc(100% + 24rpx);
text-align: center;
.footer-btn {
flex: 0 0 calc(50% - 24rpx);
margin-right: 24rpx;
}
}
</style>
uni-app签字版(ui适配iView2.x)
于 2022-10-31 11:25:40 首次发布