手写签名及签名部分截图保存如下代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写签名</title>
</head>
<style>
html,body{
padding: 0;
margin: 0;
text-align: center;
}
#canvas{
width:500px;
height: 300px;
margin: 50px auto;
background: #000;
}
.flex{
width:1200px;
margin: 0 auto;
display: flex;
justify-content: space-around;
}
.flex .img{
padding-top: 50px;
width:600px
}
</style>
<body>
<div class="flex">
<canvas id="canvas" width="500" height='300'></canvas>
<div class="img">
<img id="imgSave" src="" alt="">
</div>
</div>
<button id="clear">清空</button>
<button id="save">保存</button>
</body>
<script>
let canvas = document.getElementById('canvas'),
clear = document.getElementById('clear'),
save = document.getElementById('save'),
imgSave = document.getElementById('imgSave'),
ctx = canvas.getContext('2d')
ctx.fillStyle='#000'
ctx.fillRect(0,0,500,300)
ctx.lineWidth = 2;
ctx.strokeStyle = "white";
let cState=false;
let newR = new Render();
list=[];
function Render(){
this.move=function(e){
list.push({
x:e.offsetX,
y:e.offsetY
})
cState=true;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
this.crop=function(){
console.log(list)
let listCopy = JSON.parse(JSON.stringify(list))
let xList = list.sort((a,b)=>{
return a.x-b.x
})
let yList = listCopy.sort((a,b)=>{
return a.y-b.y
})
let width = xList[(xList.length-1)].x-xList[0].x,
height = yList[(xList.length-1)].y-yList[0].y,
x = (xList[0].x-10)>0? xList[0].x-10:0,
y=yList[0].y-10>0?yList[0].y-10:0;
let w = width+20;
h = height+20;
var imgData=ctx.getImageData(x,y,w,h);
let base64 = twoCrop(imgData,w,h);
imgSave.src=base64;
}
}
function twoCrop(imgData,w,h){
let canvas2 = document.createElement('canvas'),
ctx2 = canvas2.getContext('2d');
canvas2.width = w;
canvas2.height = h;
ctx2.fillStyle='#efefef';
ctx2.fillRect(0,0,w,h)
ctx2.putImageData(imgData,0,0);
let base = canvas2.toDataURL('image/jpeg',0.95);
return base;
}
canvas.addEventListener('mousedown',function(e){
ctx.beginPath()
ctx.moveTo(e.offsetX, e.offsetY);
this.addEventListener('mousemove',newR.move)
this.addEventListener('mouseup',mouseUp)
})
function mouseUp(){
ctx.closePath();
canvas.removeEventListener('mousemove',()=>{})
canvas.removeEventListener('mousemove',newR.move)
}
//清除
clear.addEventListener('click',function(){
ctx.clearRect(0,0,500,300)
cState=false;
list=[]
})
//保存
save.addEventListener('click',function(){
if(!cState){
alert('未签名')
return;
}
let img64 = canvas.toDataURL('image/jpeg',0.8)
//二次裁剪
newR.crop()
})
</script>
</html>