I'm building an animation that shows numbered circles going left to right. I got the animation going, but the number of each circle is always the same, and I need it to be different. I have a variable that randomizes numbers from 1 to 60, but the only way I could make it work is by calling it inside the function that draws the circle (that's why it's the same number for all circles). Can anyone nudge me in the right direction, so I can complete the code? What I have is the following (I know it's not the most elegant code, I'm still learning):
// Single Animated Circle - Get Canvas element by Id
var canvas = document.getElementById("canvas");
// Set Canvas dimensions
canvas.width = 300;
canvas.height = 900;
// Get drawing context
var ctx = canvas.getContext("2d");
// Radius
var radius = 13;
// Starting Position
var x = radius;
var y = radius;
// Speed in x and y direction
var dx = 1;
var dy = 0;
// Add random number
var randomNumber = Math.floor(Math.random() * 60) + 1;
// function generateNumbers() {
// var temp = Math.floor(Math.random() * 60) + 1;
// if (randomNumber.indexOf(temp) == -1) {
// randomNumber.push(temp);
// } else {
// i--;
// }
// }
class Circle {
constructor(data) {
this.data = data;
}
draw() {
if (
this.data.x + this.data.radius > 300 ||
this.data.x - this.data.radius < 0
) {
this.data.x = this.data.radius;
}
this.data.x += this.data.dx;
ctx.beginPath();
ctx.arc(this.data.x, this.data.y, this.data.radius, 0, Math.PI * 2, false);
ctx.stroke();
ctx.fillText(randomNumber, this.data.x - 5, this.data.y + 3);
}
}
if (randomNumber > 0 && randomNumber <= 10) {
ctx.strokeStyle = "#0b0bf1";
} else if (randomNumber > 10 && randomNumber <= 20) {
ctx.strokeStyle = "#f10b0b";
} else if (randomNumber > 20 && randomNumber <= 30) {
ctx.strokeStyle = "#0bf163";
} else if (randomNumber > 30 && randomNumber <= 40) {
ctx.strokeStyle = "#f1da0b";
} else if (randomNumber > 40 && randomNumber <= 50) {
ctx.strokeStyle = "#950bf1";
} else if (randomNumber > 50 && randomNumber <= 60) {
ctx.strokeStyle = "#0bf1e5";
}
circles = [];
circles.push(new Circle({ radius, x, y, dx, dy }));
setTimeout(function () {
circles.push(new Circle({ radius, x, y: y * 4, dx, dy }));
}, 500);
setTimeout(function () {
circles.push(new Circle({ radius, x, y: y * 8, dx, dy }));
}, 1000);
setTimeout(function () {
circles.push(new Circle({ radius, x, y: y * 12, dx, dy }));
}, 1500);
setTimeout(function () {
circles.push(new Circle({ radius, x, y: y * 16, dx, dy }));
}, 2000);
setTimeout(function () {
circles.push(new Circle({ radius, x, y: y * 20, dx, dy }));
}, 2500);
function animate3() {
requestAnimationFrame(animate3);
ctx.clearRect(0, 0, canvas.width, canvas.height);
circles.forEach((item) => item.draw());
}
//generateNumbers();
animate3();
Aucun commentaire:
Enregistrer un commentaire