代码如下:
<template>
<view>
<view style="width: 20%;">
<view @click='createCanvas'>
手写签名:
<u-image v-if="form.autographUrl" :src="form.autographUrl"
style="width: 200rpx;height: 80rpx;border: 1px solid black;"></u-image>
<view v-else style="border: 1px solid black;width: 200rpx;height: 80rpx;"></view>
</view>
</view>
<u-modal v-model="showAutograph" border-radius="14" width="605rpx" :show-title="false"
:confirm-style="{ 'font-size': '29rpx', 'color': '#341DB7' }" :show-cancel-button='true'
:cancel-style="{ 'font-size': '29rpx', 'color': '#666666' }" @confirm="confirm" @cancel="cancel">
<view class="x-modal">
<view class="x-m-title">
<text>请在框内进行签名</text>
<view class="xm-t-clear" @click="clear">
<text>清除</text>
</view>
</view>
<view class="x-m-con">
<canvas class="mycanvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
@touchend="touchend"></canvas>
</view>
</view>
</u-modal>
</view>
</template>
<script>
export default {
data() {
return {
showAutograph: false, //签名弹框是否显示
ctx: '', //绘图图像
points: [], //路径点集合
form: {
autographUrl: null,//签名
},
}
},
mounted() {
},
methods: {
createCanvas() {
this.showAutograph = true;
//创建绘图对象
this.ctx = uni.createCanvasContext("mycanvas", this);
//设置线条的粗细,单位像素,省略
this.ctx.lineWidth = 4;
this.ctx.lineCap = "round"
this.ctx.lineJoin = "round"
},
//清空画布
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);
},
})
},
draw() {
let point1 = this.points[0]
let point2 = this.points[1]
this.points.shift()
// (你想要让你手中画笔搁哪个位置上)
this.ctx.moveTo(point1.X, point1.Y)
// 绘制线条的跨越状态,从x轴开始,y轴结束,创建到达位置 (x,y)的一条线
this.ctx.lineTo(point2.X, point2.Y)
//开始绘制图像
this.ctx.stroke()
this.ctx.draw(true)
},
//关闭并清空画布
cancel() {
this.showAutograph = false;
this.clear();
},
touchend() {
this.points = [];
},
//触摸开始,获取到起点
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(); //绘制路径
}
},
//保存签名
confirm() {
let that = this;
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
fileType: 'png',
quality: 1, //图片质量
success: function (res) {
//这里的res.tempFilePath就是生成的签字图片
// console.log(res.tempFilePath);
//上传
uni.uploadFile({
url: that.vuex_config.baseUrl + '/fileUpload', // 仅为示例,非真实的接口地址
header: { Authorization: that.vuex_token },
formData: { type: "commont" },
filePath: res.tempFilePath,
name: 'files',
success(res) {
console.log(127, res);
if (res.statusCode == 200) {
const data = JSON.parse(res.data)
that.form.autographUrl = data.data[0].fileUrl
}
}
})
}
});
},
}
}
</script>