I change the text color with requestAnimationFrame(animate);
function:
requestAnimationFrame(animate);
function animate(time){
... // change text color here
if (offset_s < offset_e) {requestAnimationFrame(animate);}
}
offset_s
and offset_s
indicates start and end positions of the text for color change. In some cases the animation should last for 2 seconds, but in order cases - for 5 seconds, but offset_e - offset_s
could be the same in these two cases. What can I do to control the speed of animation based on given time in seconds/milliseconds?
From the tags of the question i can only see that you animate something drawn on canvas and thats why u cannot use css-animation or jquery-animation.
You have to control the length of the animation by calculating the time difference.
u can do it similar to this example
function start_animate(duration) {
var requestID;
var startTime =null;
var time ;
var animate = function(time) {
time = new Date().getTime(); //millisecond-timstamp
if (startTime === null) {
startTime = time;
}
var progress = time - startTime;
if (progress < duration ) {
if(offset_s < offset_e){
// change text color here
}
requestID= requestAnimationFrame(animate);
}
else{
cancelAnimationFrame(requestID);
}
requestID=requestAnimationFrame(animate);
}
animate();
}
trigger your animation and call start_animate(2000) //duration in millisecond 1000=1 sec
You should separate concerns clearly.
Have a single requestAnimationFrame running, which computes the current animation time and calls every update and draw related functions.
Then your animations would be handled by a function (or class instance if you go OOP) that deals with the current animation time.
Just some direction for the code :
var animationTime = -1;
var _lastAnimationTime = -1;
function launchAnimation() {
requestAnimationFrame(_launchAnimation);
}
function _launchAnimation(time) {
animationTime = 0;
_lastAnimationTime = time;
requestAnimationFrame(animate);
}
function animate(time){
requestAnimationFrame(animate);
var dt = time - _lastAnimationTime ;
_lastAnimationTime = time;
animationTime += dt;
// here call every draw / update functions
// ...
animationHandler.update(animationTime);
animationHandler.draw(context);
}
To start your 'engine', just call launchAnimation
then you'll have a valid animationTime
and dt
to deal with.
I'd make animationHandler
an instance of an AnimationHandler
class, that allows to add/remove/update/draw animations.
I suggest to use setInterval function in JavaScript.
requestAnimationFrame
really needs some 'ugly' calculations. Don't
believe me? Scroll up, you will see...
So, to make setInterval
function as handy as rAF(requestAnimationFrame) store the function inside of variable. Here is an example:
var gameLoop = setInterval(function() {
update();
draw();
if (gameOver)
clearInterval(gameLoop);
}, 1000/FPS);
given way, you can control your FPS and pick correct velocity for your objects.