<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
#cvs {
display: block;
background-color: gray;
border: 1px solid #000;
}
body {
margin: 0;
}
button {
cursor: pointer;
padding: 0 20px;
line-height: 60px;
border: none;
background-color: #abf;
font-size: 20px;
border-radius: 5px;
}
</style>
</head>
<body>
<canvas id="cvs" width="600" height="200">
</canvas>
<button id="clear">清空重签</button>
<button id="download">下载签名</button>
<script>
const cvs = document.querySelector('#cvs')
const btn = document.querySelector('#clear')
const ctx = cvs.getContext('2d')
let isDown = false
cvs.addEventListener('mousedown', (e) => {
isDown = true
ctx.moveTo(e.offsetX, e.offsetY)
ctx.lineWidth = 5
ctx.strokeStyle = '#fff'
})
cvs.addEventListener('mousemove', (e) => {
if (!isDown) return
ctx.lineTo(e.pageX, e.pageY)
ctx.stroke()
})
cvs.addEventListener('mouseup', () => {
isDown = false
})
btn.addEventListener('click', () => {
ctx.clearRect(0, 0, cvs.width, cvs.height)
ctx.beginPath()
})
// 点击保存签名图片
const btn_d = document.querySelector('#download')
btn_d.addEventListener('click', () => {
// 临时画布,解决保存图片无法保存画布背景色问题
const cvsd = document.createElement('canvas')
cvsd.width = '600'
cvsd.height = '200'
cvsdContext = cvsd.getContext('2d')
cvsdContext.fillStyle = 'gray'
// 先在临时画布上绘制底色
cvsdContext.fillRect(0, 0, 600, 200)
// 新建一个临时图片对象把页面上的签名画布绑定给这个图片
const signImg = new Image()
signImg.src = cvs.toDataURL('png')
signImg.onload = () => {
// 把签名图片绘制在临时画布上 这样就有了背景色
cvsdContext.drawImage(signImg, 0, 0, 600, 200)
const timestamp = Date.now().toString()
const a = document.createElement('a')
a.download = `${timestamp}.png`
a.href = cvsd.toDataURL('png')
document.body.appendChild(a)
a.click()
a.remove()
}
})
</script>
</body>
</html>
canvas实现手写签名
于 2022-09-23 15:47:56 首次发布