[aru_43]
实现思路
使用Canvas绘制线条、文本等内容生成签名图片
具体步骤:
1.监听Canvas区域鼠标或手写笔在 Canvas 上的移动、按下、释放等操作。
2.根据监听器的事件返回的参数动态绘制线条。
3.将Canvas绘制的内容转为base64图片, 通过a标签下载保存至本地。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前端打更人 - x4v.cn</title>
<style type="text/css">
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="canvas" width="360" height="200"></canvas>
<button id="clear">清除</button>
<a id="download" :href="en.content" download="签名">点击下载</a>
</body>
<script>
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
var isDrawing = false // isDrawing 用于判断鼠标是否按下
var lastX = 0
var lastY = 0 // lastX 和 lastY 用于存储上一个鼠标的位置
canvas.addEventListener('mousedown', function (e) {
isDrawing = true
;[lastX, lastY] = [e.offsetX, e.offsetY]
})
canvas.addEventListener('mousemove', function (e) {
// isDrawing 为 true,则开始绘制线条
if (isDrawing) {
ctx.beginPath()
ctx.moveTo(lastX, lastY)
ctx.lineTo(e.offsetX, e.offsetY)
ctx.stroke()
;[lastX, lastY] = [e.offsetX, e.offsetY]
}
})
canvas.addEventListener('mouseup', function () {
isDrawing = false
})
var clearBtn = document.getElementById('clear')
clearBtn.addEventListener('click', function () {
ctx.clearRect(0, 0, canvas.width, canvas.height)
})
var downloadBtn = document.getElementById('download')
function toPng() {
console.log('toPng')
var dataURL = canvas.toDataURL('image/png')
downloadBtn.href = dataURL
}
var downloadBtn = document.getElementById('download')
downloadBtn.addEventListener('click', function () {
var dataURL = canvas.toDataURL('image/png')
downloadBtn.href = dataURL
})
</script>
</html>
🎨 原创不易,支持请点赞、转载请注明本文作者为子成君