为交互添加延迟



我正在构建一个从左到右绘制多个圆圈的动画。然而,所有圆圈的动画在同一时间开始,我需要它们之间有一个定时间隔(例如1秒)。有什么办法吗?我试过setInterval,但没有成功。圆的画法如下:

function isPrime(num) {
for(var i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
const settings = {
width: 300,
height: 930,
radius: 13,
gap: 5,
circles: 30,
};
const canvas = document.getElementById("canvas");
canvas.width = settings.width;
canvas.height = settings.height;
const ctx = canvas.getContext("2d");
var randomNumber = [];

const circles = [...Array(settings.circles).keys()].map((i) => ({
number: randomNumber[i],
x: settings.radius,
y: settings.radius + (settings.radius * 2 + settings.gap) * i,
radius: settings.radius,
dx: 100, // This is the speed in pixels per second
dy: 0,
isPrime: isPrime(randomNumber[i]),
}));
function drawCircle(circle) {
i = 0;
if (circle.number > 0 && circle.number <= 10) {
ctx.strokeStyle = "#0b0bf1";
} else if (circle.number > 10 && circle.number <= 20) {
ctx.strokeStyle = "#f10b0b";
} else if (circle.number > 20 && circle.number <= 30) {
ctx.strokeStyle = "#0bf163";
} else if (circle.number > 30 && circle.number <= 40) {
ctx.strokeStyle = "#f1da0b";
} else if (circle.number > 40 && circle.number <= 50) {
ctx.strokeStyle = "#950bf1";
} else if (circle.number > 50 && circle.number <= 60) {
ctx.strokeStyle = "#0bf1e5";
}
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2, false);
ctx.stroke();
ctx.fillText(circle.number, circle.x - 5, circle.y + 3);
}
function updateCircle(circle, dt) {
circle.x = clamp(
circle.x + circle.dx * dt,
circle.radius + 1,
settings.width - circle.radius - 1
);
circle.y = clamp(
circle.y + circle.dy * dt,
circle.radius + 1,
settings.height - circle.radius - 1
);
}
function animate() {
ctx.clearRect(0, 0, settings.width, settings.height);
circles.forEach(drawCircle);
requestAnimationFrame(animate);
}
animate();
update((dt) => circles.forEach((circle) => updateCircle(circle, dt)), 50);

我认为你想做喜欢的

let i = 0, l = circles.length;
let intv = setInterval(()=>{
drawCircle(circles[i++]);
if(i === l){
clearInterval(intv); intv = undefined;
}
}, 100); // change interval as desired

代替circles.forEach(drawCircle);.

那个requestAnimationFrame看起来也很没用。

最新更新