toDataURL
方法返回一个包含图片展示的 data URI 。可以使用 type 参数其类型,默认为 PNG 格式。图片的分辨率为96dpi。
canvas.toDataURL(type, encoderOptions);
type 可选
图片格式,默认为 image/png
encoderOptions 可选
在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92。其他参数会被忽略。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- <script src="./index.js"></script> -->
<title>签名</title>
<style>
.signature {
position: relative;
}
.canvas {
width: 100%;
height: 700px;
}
.bottom {
width: 100%;
text-align: center;
height: 3rem;
line-height: 3rem;
border-top: 1px solid #ccc;
font-size: 1rem;
}
</style>
</head>
<body>
<div class="signature">
<div id="canvas" class="canvas">
</div>
<div class="bottom" onclick="submit()" style="cursor: pointer">保存签名</div>
</div>
<script>
let draw = false
window.onload = () => {
canvas()
}
function canvas() {
let c = document.getElementById("canvas")
let canvas = document.createElement("canvas")
let availHeight = document.documentElement.clientHeight
let off = 0
canvas.height = '700'
canvas.width = c.clientWidth
c.appendChild(canvas)
let dr = canvas.getContext('2d')
dr.strokeStyle = 'blue'
canvas.addEventListener('mousedown', (e) => {
draw = true
dr.beginPath()
})
canvas.addEventListener('mousemove', (e) => {
// console.log(e)
if (draw) {
dr.lineTo(e.pageX, e.pageY - off)
dr.stroke()
}
})
canvas.addEventListener('mouseup', (e) => {
// console.log(e)
draw = false
})
}
function downLoad(url) {
console.log(url)
var oA = document.createElement("a");
oA.download = '';
oA.href = url;
document.body.appendChild(oA);
oA.click();
oA.remove();
}
function submit() {
let img = document.querySelector('canvas').toDataURL("image/png")
downLoad(img)
}
</script>
</body>
</html>
文档更新时间: 2019-05-10 14:29