<template>
<view style="padding: 30rpx;">
<slot name="top"></slot>
<canvas class="my-canvas-cls" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
@touchend="touchend"></canvas>
<slot name="footer"></slot>
<view class="footer" v-if="footerShow">
<view class="left" @click="finish">保存</view>
<view class="right" @click="clear">清除</view>
<view class="close" @click="close">关闭</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
//绘图图像
ctx: '',
//路径点集合
points: [],
//签名图片
SignatureImg: ''
};
},
props: {
footerShow:{
type: Boolean,
default: true
}
},
watch: {},
methods: {
// createCanvas()----该方法主要是创建了画布
// touchstart()----触摸开始,获取到起点
// touchmove()----触摸移动,获取到路径点
// touchend()----触摸结束,将未绘制的点清空防止对后续路径产生干扰
// draw()----绘制笔迹
// clear()----清空画布
// finish()----完成绘画并保存到本地
createCanvas() {
//创建绘图对象
this.ctx = uni.createCanvasContext('mycanvas', this);
//设置画笔样式
this.ctx.lineWidth = 4;
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() {
let that = this;
uni.getSystemInfo({
success: (res)=> {
let canvasw = res.windowWidth;
let canvash = res.windowHeight;
that.ctx.clearRect(0, 0, canvasw, canvash);
that.ctx.draw(true);
this.$emit("clear",res)
}
});
},
finish() {
let that = this;
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
success: (res) => {
//这里的res.tempFilePath就是生成的签字图片
this.$emit("save", res)
}
});
},
close(){
this.$emit("close", res)
}
},
mounted() {
this.createCanvas();
}
};
</script>
<style lang="less" scoped>
.bigbox {
touch-action: none
}
.my-canvas-cls {
height: 500rpx;
width: 100%;
display: block;
position: relative;
background: #F6F6F6;
}
.footer {
font-size: 14px;
height: 150upx;
display: flex;
justify-content: space-around;
align-items: center;
padding-left: 40rpx;
.left{
background-color: #ecf5ff;
color: #a0cfff;
border-radius: 8rpx;
padding: 10rpx 15rpx;
border: 1px solid #a0cfff;
}
.right{
background-color: #fdf6ec;
color: #fcbd71;
border-radius: 8rpx;
padding: 10rpx 15rpx;
border: 1px solid #fcbd71;
}
.close{
background-color: #fef0f0;
color: #fab6b6;
border-radius: 8rpx;
padding: 10rpx 15rpx;
border: 1px solid #fab6b6;
}
}
.but-class {
margin-right: 40rpx;
}
</style>
uniapp 签名组件
最新推荐文章于 2024-07-01 19:15:19 发布