<el-dialog
title="签字"
width="80%"
append-to-body
:visible.sync="dialogVisible"
destroy-on-close
>
<canvas ref="canvas" class="jSignature" tabindex="0" @mousedown.prevent="onMouseDown"/>
<footer slot="footer" class="dialog-footer">
<el-button type="danger" :size="size" @click.native.prevent="clearPanel">清空签名</el-button>
<el-button type="primary" :size="size" @click="confirm">确认签名</el-button>
<el-button :size="size" @click="dialogVisible = false">取消</el-button>
</footer>
</el-dialog>
<script>
var app = new Vue({
el: "#app",
data() {
return {
dialogVisible: false,
},
methods: {
// 清空签名
clearPanel(e) {
this.$nextTick(() => {
const el = this.$refs["canvas"];
const ctx = el.getContext("2d");
ctx.clearRect(0, 0, el.width, el.height);
});
},
// 确认签名
confirm() {
this.$nextTick(() => {
try {
const canvas = this.$refs["canvas"];
const blank = document.createElement("canvas"); // 创建一个空canvas对象
blank.width = canvas.width;
blank.height = canvas.height;
if (canvas.toDataURL() === blank.toDataURL()) {
this.$message.error("签字格式不正确");
} else {
//执行所需操作
}
} catch (e) {
console.warn(e);
}
});
},
onMouseDown(e) {
const el = e.target || e.srcElement
const ctx = el.getContext('2d')
ctx.beginPath()
ctx.moveTo(e.offsetX, e.offsetY)
ctx.lineTo(e.offsetX, e.offsetY)
ctx.stroke()
el.onmousemove = function(e) {
if (e.which === 0) {
el.onmousemove = null
el.onmouseup = null
return
}
ctx.lineTo(e.offsetX, e.offsetY)
ctx.stroke()
}
el.onmouseup = function() {
el.onmousemove = null
el.onmouseup = null
}
el.focus()
}
});
</script>
<style>
.jSignature {
margin: 10px auto;
padding: 0px;
border: 1px dashed #aaa;
width: calc(100vw - 60px);
height: calc(100vh - 200px);
max-height: 426px;
max-width: 900px;
touch-action: none;
background-color: rgb(246, 246, 246);
display: block;
outline: none;
}
</style>
实际效果图