Am very new to canvas and javascript. I found a snippet for a starfield animation effect but it loops indefinitely. How do I get the animation to stop after say, 30 seconds? I believe it has something to do with clearInterval or setTimeout but I have no idea where in the code this should be implemented. Any help would be greatly appreciated.
window.onload = function() {
var starfieldCanvasId = "starfieldCanvas",
framerate = 60,
numberOfStarsModifier = 1.0,
flightSpeed = 0.02;
var canvas = document.getElementById(starfieldCanvasId),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
numberOfStars = width * height / 1000 * numberOfStarsModifier,
dirX = width / 2,
dirY = height / 4,
stars = [],
TWO_PI = Math.PI * 2;
for(var x = 0; x < numberOfStars; x++) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: range(0, 1)
};
}
window.setInterval(tick, Math.floor(1000 / framerate));
function tick() {
var oldX,
oldY;
context.clearRect(0, 0, width, height);
for(var x = 0; x < numberOfStars; x++) {
oldX = stars[x].x;
oldY = stars[x].y;
stars[x].x += (stars[x].x - dirX) * stars[x].size * flightSpeed ;
stars[x].y += (stars[x].y - dirY) * stars[x].size * flightSpeed ;
stars[x].size += flightSpeed;
if(stars[x].x < 0 || stars[x].x > width || stars[x].y < 0 || stars[x].y > height) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: 0
};
}
context.strokeStyle = "rgba(160, 160, 230, " + Math.min(stars[x].size, 2) + ")";
context.lineWidth = stars[x].size;
context.beginPath();
context.moveTo(oldX, oldY);
context.lineTo(stars[x].x, stars[x].y);
context.stroke();
}
}
function range(start, end) {
return Math.random() * (end - start) + start;
}
};
tickfunction) that is set on an interval; if your objective is to stop all animation (in it's present form), you would clear the timer; but irregardless to whether your objective to stop all animation or simply stop updating this animation, you would most certainly need to account for time stamps (i.e. initial timestamp that is compared to a timestamp on each loop...