【发布时间】:2020-07-27 08:21:54
【问题描述】:
我有一个 Javascript 文件,它用圆圈绘制画布。如果我点击一个圆圈,颜色必须改变。这可行,但 eventHandler 一键触发多次。因此,该程序滞后很多。我该如何改进?
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
class Circle {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
ctx.strokeStyle = this.color;
ctx.stroke();
};
update = function() {
cvs.addEventListener("click", function(e) {
var mousePosition = this.getMousePosition(e);
this.checkForCollision(mousePosition);
}.bind(this));
this.draw();
};
getMousePosition = function(e) {
var cRect = cvs.getBoundingClientRect();
var canvasX = Math.round(e.clientX - cRect.left);
var canvasY = Math.round(e.clientY - cRect.top);
return {
x: canvasX,
y: canvasY
}
}
checkForCollision = function(mPos) {
if (mPos.x < this.x + this.radius && mPos.x > this.x - this.radius && mPos.y < this.y + this.radius && mPos.y > this.y - this.radius) {
this.color = "blue";
}
}
}
var circles = [];
for (x = 0; x < 8; x++) {
for (y = 0; y < 8; y++) {
circles.push(new Circle(x * 100 + 30, y * 100 + 30, 20, "red"));
}
}
function playGame() {
requestAnimationFrame(playGame);
ctx.clearRect(0, 0, 2000, 2000);
circles.forEach(circle => circle.update());
}
playGame();
<canvas id="canvas"></canvas>
【问题讨论】:
-
您在每个绘制周期都添加一个新的点击事件,这个事件加起来很快。尝试将
addEventListener移出绘制/更新周期。 -
尝试在构造函数中只添加一次
-
@TimMG 既然您已经在
var circles = [];中声明了一个圆数组,那么您可以做的是只为点击附加一个事件侦听器,当您检测到点击时,遍历所有 Circle 对象数组以查看发生单击的鼠标位置是否在当前圆圈内。