效果图如下:
实现功能:
1、改变画笔粗细
2、保存签名实现下载功能
3、使用橡皮擦功能
4、清空画布
5、改变画笔颜色
实现代码如下
<!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>canvas实现画板</title>
<style>
.btn{
width: 600px;
display: flex;
align-items: center;
justify-content: space-around;
}
.btn span{
padding: 5px 10px;
border: 2px solid pink;
cursor: pointer;
}
.btn span:not(:last-child){
margin-right: 10px;
}
.btn input[type=color]{
height: 36px;
margin-right: 10px;
cursor: pointer;
}
canvas{
border: 2px solid #000;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="btn">
<span class="boldBtn">粗线条</span>
<span class="sinBtn">细线条</span>
<span class="saveBtn">保存签名</span>
<span class="clearBtn">橡皮擦</span>
<input class="colorBtn" type="color">
<span class="clearCanvasBtn">清空画布</span>
</div>
<script>
//创建画布
let canvas = document.createElement('canvas');
canvas.width = 600;
canvas.height = 400;
document.body.appendChild(canvas)
let ctx = canvas.getContext('2d');
ctx.lineCap = 'round';
ctx.lineJoin = 'round'
ctx.fillStyle = "#fff"
//获取按钮
let boldBtn = document.querySelector('.boldBtn');
let sinBtn = document.querySelector('.sinBtn');
let saveBtn = document.querySelector('.saveBtn');
let clearBtn = document.querySelector('.clearBtn');
let clearCanvasBtn = document.querySelector('.clearCanvasBtn');
let colorBtn = document.querySelector('.colorBtn');
let isDraw = false;
//鼠标按下
canvas.onmousedown = function(e){
isDraw = true;
let x = e.pageX;
let y = e.pageY;
// console.log(x,y);
// 获取鼠标在画布内的坐标
x = x - canvas.offsetLeft;
y = y - canvas.offsetTop;
//画线起点坐标
ctx.beginPath()
ctx.moveTo(x,y)
}
//鼠标弹起
canvas.onmouseup = function(){
//恢复为默认
ctx.globalCompositeOperation ="source-over";
isDraw = false;
//结束路径
ctx.closePath()
}
//鼠标离开
canvas.onmouseleave = function(){
ctx.globalCompositeOperation ="source-over";
isDraw = false;
ctx.closePath()
}
//鼠标移动
canvas.onmousemove = function(e){
if (!isDraw) return;
let x = e.pageX;
let y = e.pageY;
// console.log(x,y);
// 获取鼠标在画布内的坐标
x = x - canvas.offsetLeft;
y = y - canvas.offsetTop;
ctx.lineTo(x,y)
ctx.stroke()
}
//粗线条
boldBtn.onclick = function(){
ctx.lineWidth = 20
}
//细线条
sinBtn.onclick = function(){
console.log(ctx);
ctx.lineWidth = 1
}
//改变颜色
colorBtn.onchange = function(){
console.log(colorBtn.value);
//获取颜色改变值
ctx.strokeStyle = colorBtn.value
}
// 清空画布
clearCanvasBtn.onclick = function(){
//恢复为默认
ctx.clearRect(0,0,600,400)
}
// 橡皮擦
clearBtn.onclick = function(){
ctx.globalCompositeOperation ="destination-out";
ctx.lineWidth = 30;
}
//保存签名
saveBtn.onclick = function(){
let url = canvas.toDataURL()
console.log(url);
//下载签名
let a = document.createElement('a');
a.href = url;
a.download = '签名'
document.body.appendChild(a);
a.click();
document.body.removeChild(a)
}
</script>
</body>
</html>