简单介绍橡皮擦功能思路,代码demo自己看看就好了,一点都不复杂:
- 确认橡皮擦大小,可动态设置;
- 鼠标按下记录点击的坐标,然后根据设置的橡皮擦大小画一个圆,最后清除该圆形区域坐标范围的颜色信息;然后创建鼠标移动事件;
- 按下后鼠标移动过程中对移动的轨迹坐标进行清除颜色信息。
- 移动过程中,为了解决鼠标移动事件响应是有时间间隔的,导致正常情况下鼠标快速移动时出现橡皮擦擦除颜色不连贯的问题,为此需要每次擦除需记录上个坐标点,然后对当前坐标点连起来,连起来的范围就是要擦除的坐标范围;
- 鼠标松开销毁移动事件;
没有6了兄弟,功能就是这么简单;
<!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>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#c {
position: absolute;
width: 800px;
height: 600px;
top: 0;
left: 0;
border: 1px solid black;
}
#background {
font-size: 40px;
width: 800px;
height: 600px;
user-select: none;
overflow: hidden;
}
</style>
</head>
<body>
<div id="background">
这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图,这是底图
</div>
<canvas id="c" width="800" height="600"></canvas>
<div>
<button id="hehe">爱尔奎特</button>
</div>
<script>
const eraserWidth = 30;
var ctx = c.getContext("2d");
ctx.fillStyle = "#336699";
ctx.fillRect(0, 0, c.width, c.height);
ctx.globalCompositeOperation = "destination-out";
let beginP = { x: 0, y: 0 };
c.onmousedown = function (e) {
beginP.x = e.offsetX;
beginP.y = e.offsetY;
ctx.beginPath();
ctx.arc(beginP.x, beginP.y, eraserWidth / 2, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
c.onmousemove = function (e) {
var tx = e.offsetX;
var ty = e.offsetY;
ctx.beginPath();
ctx.lineJoin = ctx.lineCap = "round";
ctx.lineWidth = eraserWidth;
ctx.moveTo(beginP.x, beginP.y);
ctx.lineTo(tx, ty);
ctx.closePath();
ctx.stroke();
beginP.x = tx;
beginP.y = ty;
};
};
c.onmouseup = function () {
c.onmousemove = "null";
};
</script>
</body>
</html>