碎碎念

今天测试突然给我提了一个手机签名的需求,第一时间想到了用组件写,但是这里我不得不吐槽一个这是一个老项目, 用的 bootstrapMui 框架,这里我不得不吐槽一下这种写完了有什么意义毕竟都是快被淘汰的框架。没办法在网上搜索了一下用 JS 写了一个简单的签名。

Canvas

是 HTML5 提供的一种新标签, ie9 才开始支持的,Canvas 是一个矩形区域的画布,可以用 JS 控制每一个像素在上面绘画。canvas 标签使用 JavaScript 在网页上绘制图像,本身不具备绘图功能。canvas 拥有多种绘制路径,矩形,圆形,字符以及添加图像的方法。这里我们也是用 Canvas 实现签名。之前的项目写过一个 Vue 版本的签名,说到底都是大同小异,底层都是 Canvas

代码

  • 这里我们就列出一些主要的代码,具体功能可以根据自己的需求在更改
  • 准备工作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 获取canvas
const myCanvas = document.getElementById("canvas");
const canvasWidth = document.documentElement.clientWidth - 20;
const canvasHeight = 300;
myCanvas.setAttribute('width', canvasWidth);
myCanvas.setAttribute('height', canvasHeight);
//获取2d对象
const ctx = myCanvas.getContext("2d");
//清空画布
const clear = document.getElementById("clear");
clear.addEventListener("click", function () {
myCanvas.width = myCanvas.width;
});
//线条
const selWidth = document.getElementById("selWidth");
// 颜色
const selColor = document.getElementById("selColor");
// 保存签名
const imgInfo = document.getElementById("imgInfo");
// 保存的盒子
const imgs = document.getElementById("imgs");
//控制线条是否画
let isMouseMove = false;
//线条位置
let lastX, lastY;
let widthVal = selWidth[0].value, colorVal = selColor[0].value;
  • 画线
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function drawLine(x, y, isT) {
if (isT) {
ctx.beginPath();
ctx.lineWidth = widthVal; //设置线宽状态
ctx.strokeStyle = colorVal; //设置线的颜色状态
ctx.lineCap = 'round'
ctx.lineJoin = "round";
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
}
// 每次移动都要更新坐标位置
lastX = x;
lastY = y;
}
  • 线条粗细
1
2
3
4
function lineCrude() {
let activeIndex = selWidth.selectedIndex;
widthVal = selWidth[activeIndex].value;
}
  • 改变颜色
1
2
3
4
function setColor() {
let activeIndex = selColor.selectedIndex;
colorVal = selColor[activeIndex].value;
}
  • 验证canvas画布是否为空函数
1
2
3
4
5
6
function isCanvasBlank(canvas) {
const blank = document.createElement('canvas'); //系统获取一个空canvas对象
blank.width = canvas.width;
blank.height = canvas.height;
return canvas.toDataURL() == blank.toDataURL(); //比较值相等则为空
}
  • 保存图片,通过 toDataURL() 把得到的base64图片传到后台转换成jpg或者png。