Как я могу добавить несколько шаров на один холст, используя один и тот же класс, но каждый раз меняя его значения? Например, сначала синий шар, который перемещается вправо, а затем через 5 секунд появляется красный шар, который перемещается в другом направлении. И как я могу хранить все эти шары в массиве?
Я попытался просто повторить «новый шар (...)» с теми же переменными, что и предыдущий, где каждая переменная содержит случайное число, думая, что они будут менять это случайное значение каждый раз, когда я создаю новый шар из этого учебный класс. Но ничего не происходит, или я думаю, что он просто создает новый шар точно такой же и поверх последнего. Я также попробовал это, только с функцией, которая повторяется каждые 5 секунд, но тот же результат.
<!Doctype html>
<html>
<head>
<title>Ballgame</title>
<meta charset="utf-8">
</head>
<style>
canvas{
background-color: lightgrey;
outline:2px solid black;
margin-top:20;
}
div{
width:200px;
height:200px;
background-color: red;
margin: 100px auto;
}
</style>
<body>
<center>
<canvas id="canvas" height="600" width="800"></canvas>
</center>
<audio src="Media/bounce.mp3">
<script>
"use strict"
var canvas = document.getElementById("canvas");
var canvasContext = canvas.getContext("2d");
var bounce = document.querySelector("audio")
var color;
var radius;
var posNeg = [-1,1]
var speedx = 5 * posNeg[Math.floor(Math.random()*2)];
var speedy = 3 * posNeg[Math.floor(Math.random()*2)];
var randomx = Math.floor(Math.random()*700 +50)
var randomy = Math.floor(Math.random()*500 +50)
class Ball{
constructor(x, y, speedx,speedy, radius, color){
color = "hsla(" + Math.floor(Math.random()*360+1) + ", 100%, 50%, 1)";
radius = Math.floor(Math.random()*30 +2);
this.x = x;
this.y = y;
this.speedx = speedx;
this.speedy = speedy;
this.radius = radius
this.color = color
}
draw(){
canvasContext.beginPath ();
canvasContext.arc(this.x,this.y,this.radius,0,Math.PI *2);
canvasContext.strokeStyle = "black";
canvasContext.lineWidth = 5;
canvasContext.stroke();
canvasContext.fillStyle = this.color;
canvasContext.fill();
canvasContext.closePath();
}
move(){
this.x += this.speedx;
this.y += this.speedy;
if(this.x - this.radius < 0 || this.x +this.radius > canvas.width){
this.speedx = -1 * this.speedx;
bounce.play()
}
if(this.y - this.radius < 0 || this.y + this.radius > canvas.height){
this.speedy = -1 * this.speedy;
bounce.play()
}
}
}
var ball = new Ball(randomx, randomy, speedx, speedy, radius, color)
function animate(){
canvasContext.clearRect (0,0,canvas.width,canvas.height);
ball.move();
ball.draw();
requestAnimationFrame(animate);
}
setInterval(function(){
new Ball(randomx, randomy, speedx, speedy, radius, color);
}, 5000)
requestAnimationFrame(animate);
</script>
</body>
</html>
Как я уже говорил ранее, я думаю, что он просто печатает новый шар, который точно такой же, как и поверх предыдущего мяча. Следовательно, я не вижу никакой разницы. Я хочу, чтобы он создал новый шар, но с другими значениями, например разным цветом, радиусом и направлением.