<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<canvas></canvas>
<div>
<button onclick="cancel()">取消</button>
<button onclick="save()">保存</button>
</div>
</body>
<script>
const config = {
width: 400,
height: 200,
lineWidth: 5,
strokeStyle: 'red',
lineCap: 'round',
lineJoin: 'round',
}
const canvas = document.querySelector('canvas')
canvas.width = config.width
canvas.height = config.height
canvas.style.border = '1px solid #000'
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'transparent'
ctx.fillRect(
0,
0,
config.width,
config.height
);
const client = {
offsetX: 0,
offsetY: 0,
endX: 0,
endY: 0
}
const mobileStatus = (/Mobile|Android|iPhone/i.test(navigator.userAgent))
const init = event => {
const { offsetX, offsetY, pageX, pageY } = mobileStatus ? event.changedTouches[0] : event
client.offsetX = offsetX
client.offsetY = offsetY
client.endX = pageX
client.endY = pageY
ctx.beginPath()
ctx.lineWidth = config.lineWidth
ctx.strokeStyle = config.strokeStyle
ctx.lineCap = config.lineCap
ctx.lineJoin = config.lineJoin
ctx.moveTo(client.endX, client.endY)
window.addEventListener(mobileStatus ? "touchmove" : "mousemove", draw)
}
const draw = event => {
const { pageX, pageY } = mobileStatus ? event.changedTouches[0] : event
client.endX = pageX
client.endY = pageY
ctx.lineTo(pageX, pageY)
ctx.stroke()
}
const cloaseDraw = () => {
ctx.closePath()
window.removeEventListener("mousemove", draw)
}
window.addEventListener(mobileStatus ? "touchstart" : "mousedown", init)
window.addEventListener(mobileStatus ? "touchend" : "mouseup", cloaseDraw)
const cancel = () => {
ctx.clearRect(0, 0, config.width, config.height)
}
const save = () => {
canvas.toBlob(blob => {
const date = Date.now().toString()
const a = document.createElement('a')
a.download = `${date}.png`
a.href = URL.createObjectURL(blob)
a.click()
a.remove()
})
}
</script>
</html>