<!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>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div
style="
background-color: pink;
width: 400px;
height: 400px;
margin: 0 auto;
margin-top: 200px;
"
>
<canvas></canvas>
<div>
<button onclick="cancel()">取消</button>
<button onclick="save()">保存</button>
</div>
</div>
</body>
<script>
const config = {
width: 400,
height: 400,
lineWidth: 3,
strokeStyle: "#000",
lineCap: "round",
lineJoin: "round",
};
const canvas = document.querySelector("canvas");
canvas.width = config.width;
canvas.height = config.height;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "transparent";
ctx.fillRect(0, 0, config.width, config.height);
const mobileStatus = /Mobile|Android|iPhone/i.test(navigator.userAgent);
const draw = (event) => {
const { offsetX, offsetY } = mobileStatus
? event.changedTouches[0]
: event;
ctx.lineTo(offsetX, offsetY);
ctx.stroke();
};
const init = (event) => {
const { offsetX, offsetY, pageX, pageY } = mobileStatus
? event.changedTouches[0]
: event;
ctx.beginPath();
ctx.lineWidth = config.lineWidth;
ctx.strokeStyle = config.strokeStyle;
ctx.lineCap = config.lineCap;
ctx.lineJoin = config.lineJoin;
ctx.moveTo(offsetX, offsetY);
canvas.addEventListener(mobileStatus ? "touchmove" : "mousemove", draw);
};
canvas.addEventListener(mobileStatus ? "touchstart" : "mousedown", init);
const cloaseDraw = () => {
ctx.closePath();
canvas.removeEventListener("mousemove", draw);
};
canvas.addEventListener(mobileStatus ? "touchend" : "mouseup", cloaseDraw);
canvas.addEventListener("mouseout", 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");
console.log(URL.createObjectURL(blob));
a.download = `${date}.png`;
a.href = URL.createObjectURL(blob);
a.click();
a.remove();
});
};
</script>
</html>
