Вечер добрый! Подскажите как сделать остановку анимации по нажатию на кнопку stop и кто может оцените код, может что-то нужно изменить? Забыл добавить, чтобы и очищался экран от квадратов
function play() {
requestAnimationFrame(animate);
}
function animate() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var score = document.getElementById('score');
var count = 1;
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() * 3;
}
}
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++;
}
}
}
var clearSquares = function() {
score.innerHTML = count = 0;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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="play()" "> Start </button>
<button onclick="stop()"> Stop </button>
<span> Score: <span id="score"> 0 </span> </span>
</div>
<canvas width="640" height="480" id="canvas"></canvas>
</body>
</html>