Canvas rotate circle in certain speed using RequestAnimationFrame

canvas, javascript, requestanimationframe, rotation

Solution

Simply use a time-diff approach locking the steps to the difference between old and new time:

DEMO

Start with getting current time:

var oldTime = getTime();

/// for convenience later
function getTime() {
    return (new Date()).getTime();
}

Then in your loop:

function Update(){

    var newTime = getTime(),       /// get new time
        diff = newTime - oldTime;  /// calc diff between old and new time
    
    oldTime = newTime;             /// update old time
    
    ...
    
    currentAngle += diff * 0.001;  /// use diff to calc angle step

    /// reset angle
    currentAngle %= 2 * Math.PI;

    raf(Update);
}

Using this approach will bind the animation to time instead of FPS.

Update For one minute I thought MODing the angle wouldn't work with floats, but you can (had to double check) so code updated.

Problem

I made a quick simple solution in JSFiddle, for better and faster explaining: ``` var Canvas = document.getElementById("canvas"); var ctx = Canvas.getContext("2d"); var startAngle = (2*Math.PI); var endAngle = (Math.PI*1.5); var currentAngle = 0; var raf = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame; function Update(){ //Clears ctx.clearRect(0,0,Canvas.width,Canvas.height); //Drawing ctx.beginPath(); ctx.arc(40, 40, 30, startAngle + currentAngle, endAngle + currentAngle, false); ctx.strokeStyle = "orange"; ctx.lineWidth = 11.0; ctx.stroke(); currentAngle += 0.02; document.getElementById("angle").innerHTML=currentAngle; raf(Update); } raf(Update); ``` http://jsfiddle.net/YoungDeveloper/YVEhE/3/ As the browser chooses the fps, how would I rotate the ring independently from frame speed. Because for now, if speed is 30fps it will rotate slower, but if 60fps faster, because its rotate amount is added for each call. As i understand from couple of thread it has something to do with getTime, i really tried but could not get it done, i would need to rotate it once in 10 seconds. The other thing is, angle, it will increase more and more, and after long long time it will crash because variable max amount will be exceeded, so how do i make seamless rotate cap ? Thank you for reading!

Original source