一、业务场景:最近接触到流程审批的一些流程,需要人员在最终的结果中进行手工的电子签名。
二、解决方案:在canavas画布上进行线条绘制,通过给画布添加鼠标按下(mousedown)、移动(mousemove)、以及抬起(mouseup)的事件,操作事件对象的事件源中的参数值,对线条颜色和粗细进行绘制,形成最终的电子签名结果
三、实现过程:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>电子签名</title>
</head>
<style>
#canvas {
border: 1px solid #999;
}
</style>
<body>
<div>
画笔颜色:<input type="color" id="ipt"></input>
画笔粗细:<select id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<canvas id="canvas" width="500" height="500"></canvas>
<br />
<button id="btn">清除画布</button>
</body>
<script>
// 获取画布的Dom节点
const canavas = document.getElementById("canvas");
// 获取颜色框的Dom节点
const ipt = document.getElementById("ipt");
// 获取字体粗细的Dom节点
const select = document.getElementById("select");
// 获取清除按钮的Dom节点
const btn = document.getElementById("btn");
// 获取画布上下文对象
const context = canavas.getContext("2d");
// 鼠标状态
let mouseState = false;
// 线条颜色
let color = '#000'
// 线条粗细
let lineWidth = 1
// 处理鼠标按下事件
canavas.addEventListener("mousedown", (e) => {
mouseState = true;
if (mouseState) {
// 设置起始坐标点
context.moveTo(e.offsetX, e.offsetY);
}
});
// 处理鼠标移动事件
canavas.addEventListener("mousemove", (e) => {
if (mouseState) {
// 设置绘制坐标
context.lineTo(e.offsetX, e.offsetY);
// 设置字体颜色
context.strokeStyle = color;
// 设置字体粗细
context.lineWidth = lineWidth;
// 描边绘制
context.stroke();
}
});
// 处理鼠标抬起事件
canavas.addEventListener("mouseup", (e) => {
mouseState = false;
});
// 清空画布
btn.onclick = function clearcanavas() {
canavas.width = 500;
canavas.height = 500;
};
// 处理颜色改变事件
ipt.addEventListener('change', (e) => {
// 开启一个独立作用域
context.beginPath();
// 从事件对象的事件源中获取颜色值
color = e.target.value
})
// 处理字体粗细改变事件
select.addEventListener('change', (e) => {
// 从事件对象的事件源中获取线条粗细值
lineWidth = e.target.value
})
</script>
</html>
四、效果展示
今天的分享到此结束,欢迎小伙伴们一起交流