<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
margin: 0
padding: 0
width: 100%
height: 100%
}
.sing_demo {
box-sizing: border-box
padding: 10px 0
}
display: block
margin: 20px auto
border: 1px solid
}
.btn_box {
display: flex
width: 100%
margin: 20px auto
justify-content: space-around
align-items: center
}
display: block
margin: 0 auto
}
</style>
</head>
<body>
<div class="sing_demo">
<canvas id="sign_box" width="360px" height="220px"></canvas>
<!-- canvas只能行内设置宽高 -->
<div class="btn_box">
<button id="clear">清空签名</button>
<button id="finish">生成图片</button>
</div>
<img src="" alt="" id="show">
</div>
<script>
const can = document.getElementById('sign_box')
const clear = document.getElementById('clear')
const finish = document.getElementById('finish')
const show = document.getElementById('show')
const ctx = can.getContext('2d')
ctx.lineWidth = 4
//圆润笔记
ctx.linecap = 'round'
ctx.lineJoin = 'round'
const t = can.offsetTop
const l = can.offsetLeft
let x = null
let y = null
can.ontouchstart = function (e) {
x = e.touches[0].pageX - l
y = e.touches[0].pageY - t
ctx.beginPath()
ctx.moveTo(x, y)
}
can.ontouchmove = function (e) {
x = e.touches[0].pageX - l
y = e.touches[0].pageY - t
ctx.lineTo(x, y)
ctx.stroke()
}
can.ontouchend = function (e) {
x = e.changedTouches[0].pageX - l
y = e.changedTouches[0].pageY - t
ctx.closePath()
}
clear.onclick = function(){
ctx.clearRect(0,0,300,200)
}
finish.onclick = function(){
let src = can.toDataURL('image/png')
show.src = src
console.log(src)
}
</script>
</body>
</html>