
DOCTYPE html>
<html lang="en">
<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>Documenttitle>
<style>
.active {
color: red;
}
style>
head>
<body>
<canvas id="c1" width="800" height="400">canvas>
<hr />
<button id="boldBtn">粗线条button>
<button id="thinBtn">细线条button>
<button id="saveBtn">保存签名button>
<button id="downloadBtn">下载签名button>
<input type="color" id="color" value="" />
<button id="clearBtn">橡皮擦button>
<button id="nullBtn">清空画布button>
<script>
// 1. 获取canvas画布和绘制的上下文对象
/** @type {HTMLCanvasElement} */
var canvas = document.querySelector("#c1");
var ctx = canvas.getContext("2d");
// 连接处圆润
ctx.lineJoin = "round";
// 开头和结束端圆润
ctx.lineCap = "round";
// 2. 获取输入框和按钮
// 设置画笔的粗细
var boldBtn = document.querySelector("#boldBtn");
var thinBtn = document.querySelector("#thinBtn");
var saveBtn = document.querySelector("#saveBtn");
var downloadBtn = document.querySelector("#downloadBtn");
var clearBtn = document.querySelector("#clearBtn");
var nullBtn = document.querySelector("#nullBtn");
var inputColor = document.querySelector("#color");
// 设置允许绘制的变量
var isDraw = false;
// 鼠标按下
canvas.onmousedown = function () {
isDraw = true;
ctx.beginPath();
let x = event.pageX - canvas.offsetLeft;
let y = event.pageY - canvas.offsetTop;
ctx.moveTo(x, y);
};
// 鼠标离开
canvas.onmouseleave = function () {
isDraw = false;
ctx.closePath();
};
// 鼠标抬起
canvas.onmouseup = function () {
isDraw = false;
ctx.closePath();
};
// 鼠标移动
canvas.onmousemove = function () {
if (isDraw) {
let x = event.pageX - canvas.offsetLeft;
let y = event.pageY - canvas.offsetTop;
ctx.lineTo(x, y);
ctx.stroke();
}
};
boldBtn.onclick = function () {
ctx.globalCompositeOperation = "source-over";
ctx.lineWidth = 20;
boldBtn.classList.add("active");
thinBtn.classList.remove("active");
clearBtn.classList.remove("active");
};
thinBtn.onclick = function () {
ctx.globalCompositeOperation = "source-over";
ctx.lineWidth = 2;
thinBtn.classList.add("active");
boldBtn.classList.remove("active");
clearBtn.classList.remove("active");
};
clearBtn.onclick = function () {
ctx.globalCompositeOperation = "destination-out";
ctx.lineWidth = 30;
clearBtn.classList.add("active");
boldBtn.classList.remove("active");
thinBtn.classList.remove("active");
};
nullBtn.onclick = function () {
ctx.clearRect(0, 0, 800, 400);
};
// 保存生成图片
saveBtn.onclick = function () {
let urlData = canvas.toDataURL();
let img = new Image();
img.src = urlData;
document.body.appendChild(img);
};
// 下载画布图片
downloadBtn.onclick = function () {
let urlData = canvas.toDataURL();
let downloadA = document.createElement("a");
downloadA.setAttribute("download", "签名");
downloadA.href = urlData;
downloadA.click();
};
// 改变颜色
inputColor.onchange = function () {
ctx.strokeStyle = inputColor.value;
};
script>
body>
html>