效果图👇
代码不多直接粘在这里
<template>
<div class="border">
<canvas
ref="canvas"
width="800"
height="500"
class="border-success"
tabindex="0"
@mousedown="onMouseDown"
/>
<footer slot="footer" class="dialog-footer text-center">
<button type="danger" @click.native.prevent="clearPanel">清空</button>
<button type="primary" @click="confirm">确认</button>
</footer>
<img class="imgCanvas" :src="imgUrl" />
</div>
</template>
<script>
import { defineComponent, ref, nextTick } from "vue";
export default defineComponent({
name: "environAmbitus",
setup() {
const canvas = ref(null);
const imgUrl = ref();
// 开始签名
function onMouseDown(e) {
const el = e.target || e.srcElement; //获取事件源
const ctx = el.getContext("2d"); //获取canvas的上下文
ctx.lineWidth = 3; //线条宽度
ctx.beginPath(); //开始路径绘制
ctx.moveTo(e.offsetX, e.offsetY); //设置路径起点,坐标为(20,20)
ctx.lineTo(e.offsetX, e.offsetY); //设置路径终点,坐标为(200,20)
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();
}
// 清空签名
function clearPanel(e) {
nextTick(() => {
// const el = canvas;
const ctx = canvas.value.getContext("2d");
ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
});
}
// 确认签名
function confirm() {
nextTick(() => {
try {
// const canvas = this.$refs["canvas"];
const blank = document.createElement("canvas"); // 创建一个空canvas对象
blank.width = canvas.value.width;
blank.height = canvas.value.height;
imgUrl.value = canvas.value.toDataURL();// 将画布上的内容导出为图片
} catch (e) {
console.warn(e);
}
});
}
return { onMouseDown, confirm, clearPanel, canvas, imgUrl };
}
});
</script>
<style scoped>
.border {
width: 800px;
height: 500px;
border: 1px solid skyblue;
box-sizing: border-box;
}
</style>
需要注意的是 可绘制区域是canvas的height width控制的,用的话可以给他改成父组件传递的