Объясните пожайлуста, почему счетчик работает непонятно как. Я хотел чтобы он считал количество удалённых квадратов из массива.
function animate() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var score = document.getElementById('score');
var count = 0;
function Square (x, y, w, h) {
this.x = Math.random() * 620;
this.y = y;
this.w = w;
this.h = h;
this.r = Math.round(Math.random() * 255);
this.g = Math.round(Math.random() * 255);
this.b = Math.round(Math.random() * 255);
this.rgba = "rgba("+this.r+", "+this.g+", "+this.b+", 1)";
this.draw = function() {
ctx.fillStyle = this.rgba;
ctx.fillRect(this.x, this.y, 20, 20);
this.update();
}
this.update = function() {
this.y += Math.random() * 2;
}
}
var squares = [];
function draw() {
ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientWidth);
for(i = 0; i < squares.length; i++)
squares[i].draw();
update();
}
function update() {
for (var i = 0; i < squares.length; i++) {
squares[i].update();
}
}
setInterval(function(){
squares.push(new Square(0, 0, 20, 20))
},1000);
setInterval(draw, 20);
var isCursorInSquares = function(x, y, squares) {
return x > squares.x && x < squares.x + squares.w + 8 &&
y > squares.y && y < squares.y + squares.h + 20;
}
canvas.onclick = function(e) {
var x = e.pageX;
y = e.pageY;
for(var i = squares.length - 1; i >= 0; --i) {
if(isCursorInSquares(x, y, squares[i]))
delete squares.splice(i, 1);
score.innerHTML = count++;
}
}
}
document.body.onload = animate;
<doctype html>
<html>
<head>
<title> Qualium Systems Javascript test task </title>
<script type="text/javascript" src="main.js"></script>
<style>
canvas {
background: yellow;
}
</style>
</head>
<body>
<div>
<button onclick=""> Start </button>
<button onclick=""> Stop </button>
<span> Score: <span id="score"> 0 </span> </span>
</div>
<canvas width="640" height="480" id="canvas"></canvas>
</body>
</html>