I've got a Javascript file which draws a canvas with circles. If I click on a circle, the color must change. This works, but the eventHandler fires many times with one click. Because of this, the program lags a lot. How do I improve this?
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>