2 回答
TA贡献1783条经验 获得超4个赞
为了实现这一点,我声明了一个新变量:frames帧会随着每一animate()帧增加它的值。
我在里面创建圆圈animate(),只有当
if(frames % 27 == 0 && //you can choose a different number
Math.random() < .5 && // for randomness
circleArray.length <= 10){//limiting the total number of circles at 10
circleArray.push(new Circle());}
我希望这是你想要达到的目标。
var canvas = document.getElementById("canvas");
var g = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var frames = 0;
//object
function Circle() {
this.array = [100, 300, 400, 200];
this.radius = 40;
this.x = innerWidth + this.radius;
this.y = this.array[Math.floor(Math.random() * 4)];
this.speed = -Math.floor(Math.random() * (20 - 4)) + 4;
//methods for the object
this.draw = function() {
g.beginPath();
g.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
g.closePath();
g.fill();
};
this.update = function() {
this.x += this.speed;
// if the circle goes out of the canvas put it back
if(this.x < -this.radius){this.x = innerWidth + this.radius;}
this.draw();
};
}
var circleArray = [];
function animate() {
requestAnimationFrame(animate);
g.clearRect(0, 0, innerWidth, innerHeight);
if(frames % 27 == 0 &&
Math.random() < .5 &&
circleArray.length <= 10){circleArray.push(new Circle());}
for (var i = 0; i < circleArray.length; i++) {
circleArray[i].update();
}
drawLines();
frames++
}
animate();
function drawLines(){
//lines
g.beginPath();
g.moveTo(0, 100);
g.lineTo(innerWidth, 100);
g.strokeStyle = "red";
g.stroke();
g.closePath();
g.beginPath();
g.moveTo(0, 200);
g.lineTo(innerWidth, 200);
g.strokeStyle = "red";
g.stroke();
g.closePath();
g.beginPath();
g.moveTo(0, 300);
g.lineTo(innerWidth, 300);
g.strokeStyle = "red";
g.stroke();
g.closePath();
g.beginPath();
g.moveTo(0, 400);
g.lineTo(innerWidth, 400);
g.strokeStyle = "red";
g.stroke();
g.closePath();
}
<canvas id="canvas"></canvas>
TA贡献1821条经验 获得超6个赞
如果您希望抽奖之间有随机的时间量,则 setInterval 可能不是您想要使用的。尝试做这样的事情:
let randomDelay
for(int i = 0; i < circleArray.length; i++){
randomDelay = Math.random() * 100 //maximum number of milliseconds to wait
setTimeout(() => {
circleArray[i].update()
}, randomDelay)
}
您的代码没有按照您的预期执行的原因是因为您的 for 循环在间隔内,这意味着所有这些都每 1 秒“同时”更新一次
添加回答
举报