希望你天天开心
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>绘画板</title>
<style>
#canvas {
border: 1px solid black;
border-radius: 5px;
}
.menu {
display: flex;
}
.button {
margin: 5px;
}
</style>
</head>
<body>
<div class="menu">
<div class="button">画板</div>
<div class="button" id="clear">重置</div>
<div class="button" id="save">保存</div>
</div>
<div class="window">
<div class="top">
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
</div>
</div>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
let painting = false; // 记录绘画
let startPoint = { x: undefined, y: undefined }; // 记录起点的位置
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// 鼠标点击
canvas.onmousedown = (e) => {
let x = e.offsetX;
let y = e.offsetY;
startPoint = { x: x, y: y };
painting = true;
}
// 鼠标移动
canvas.onmousemove = (e) => {
let x = e.offsetX;
let y = e.offsetY;
let newPoint = { x: x, y: y };
if (painting) {
drawLine(startPoint.x, startPoint.y, newPoint.x, newPoint.y);
startPoint = newPoint;
}
}
// 鼠标离开
canvas.onmouseup = () => {
painting = false;
}
// 绘制方法
function drawLine(xStart, yStart, xEnd, yEnd) {
ctx.beginPath();
ctx.lineWidth = 3;
ctx.moveTo(xStart, yStart);
ctx.lineTo(xEnd, yEnd);
ctx.stroke();
ctx.closePath();
}
clear.onclick = () => {
ctx.fillStyle = "#fff";
ctx.clearRect(0, 0, canvas.width, canvas.height);
// ctx.fillRect(0, 0, canvas.width, canvas.height); // 同上面效果一致
}
save.onclick = () => {
const url = canvas.toDataURL("image/jpg");
const a = document.createElement("a");
a.href = url;
a.download = "画板";
a.target = "_blank";
a.click();
}
</script>
</body>
</html>