Animate needle movement in Gauge chart

1.7k Views Asked by At

I'm using the solution here to plot a speedometer gauge. This is built with Flot charts. I'm trying to animate the movement of the needle. I want the needle to move slowly from start to end.

Here is what I have so far.

updatePlot = function(actual_length){

        var data = [[0,0],positionOnArc(actual_length * 100)];
        $('.gauge-div').delay( 8000 ).plot([data], options);
    
    }

    //The logic: devide one move into 25 moves and add a delay between each move

    var diff_length = Math.abs(prev_move_length - move_length) / 25;

    for(var i=0; i<25; i++) {
        
        if (prev_move_length < move_length) {
            var actual_length = prev_move_length + i * diff_length;
        } else {
            var actual_length = prev_move_length - i * diff_length;
        }
        
        setTimeout(updatePlot(actual_length), 1000);
    }

As you can see I'm trying to delay the loop iteration with setTimeout and delay. But I'm not able to animate the needle movement.

Can you help me to solve this?

Thanks in Advance.

1

There are 1 best solutions below

1
On BEST ANSWER

There's a clever way to use jquery animate (found here) by passing in our own step function, which in this case would move the needle.

Sample code:

var updatePlot = function(pos) {        
    var data = [[0,0],positionOnArc(pos)];
    $('#placeholder').plot([data], options);
};

// starting position   
updatePlot(0);

$({foo:0})              // from 0 to
.delay(1000)            // (wait for it..)
.animate({foo:100}, {   // 100
    step: updatePlot,
    duration: 4300      // in 4.3 seconds
}).animate({foo:0}, {   // and back to 0
    step: updatePlot,
    duration: 1000      // in 1 second
});

Fiddle: http://jsfiddle.net/YGcYJ/217/