<!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>Document</title>
<style>
.active {
color: #fff;
background-color: orangered;
}
</style>
</head>
<body>
<canvas id="c1" width="800" height="600" style="border:1px solid #d3d3d3;"></canvas>
<hr/>
<button id="boldBtn" type="button">粗线条</button>
<button id="thinBtn" type="button">细线条</button>
<button id="saveBtn" type="button">保存签名</button>
<input type="color" name="" id="color">
<button class="clearBtn" type="button">橡皮檫</button>
<button id="nullBtn" type="button">清空画布</button>
</body>
<script>
//1.获取画笔
var canvas = document.querySelector("#c1");
var ctx = canvas.getContext("2d");
//链接处圆润
ctx.lineJoin = "round";
// 开端和结束也是圆的
ctx.lineCap = "round";
//2.获取输入框和按钮
//2.1设置画笔的粗细
//粗线条
var boldBtn = document.querySelector("#boldBtn");
// 细线条
var thinBtn = document.querySelector("#thinBtn");
// 选择的颜色
var inputColor = document.querySelector("#color");
// 保存画布
var saveBtn = document.querySelector("#saveBtn");
// 橡皮檫
var clearBtn = document.querySelector(".clearBtn");
// 清空画布
var nullBtn = document.querySelector("#nullBtn");
// 设置允许绘制的变量
var isDraw = false;
// 鼠标移入事件
canvas.onmousedown = function() {
isDraw = true;
ctx.beginPath();
var x = event.pageX - canvas.offsetLeft;
var y = event.pageY - canvas.offsetTop;
ctx.moveTo(x, y);
}
// 鼠标离开事件
canvas.onmouseleave = function() {
isDraw = true;
ctx.closePath();
}
// 鼠标释放事件
canvas.onmouseup = function() {
isDraw = true;
ctx.closePath();
}
// 鼠标离开事件
canvas.onmousemove = function(event) {
if (isDraw) {
var x = event.pageX - canvas.offsetLeft;
var 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;
}
// 清空画布点击事件
nullBtn.onclick = function() {
ctx.clearRect(0, 0, 800, 600);
}
// 保存签名
saveBtn.onclick = function() {
var urlData = canvas.toDataURL();
var img = new Image();
img.src = urlData;
// document.body.appendChild(img);
var downloadA = document.createElement('a');
downloadA.setAttribute('download', '酷炫签名');
downloadA.href = urlData;
downloadA.click();
}
inputColor.onchange = function() {
ctx.strokeStyle = inputColor.value;
}
</script>
</html>
效果图: