Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move canvas speedometer needle slowly?

I use following codes in order to move a picture in canvas for my speedometer.

var meter = new Image,
    needle = new Image;
window.onload = function () {
    var c = document.getElementsByTagName('canvas')[0];
    var ctx = c.getContext('2d');
    setInterval(function () {
        ctx.save();
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.translate(c.width / 2, c.height / 2);
        ctx.drawImage(meter, -165, -160);
        ctx.rotate((x * Math.PI / 180);
        / x degree   
            ctx.drawImage( needle, -13, -121.5 );
            ctx.restore();
        },50);
    };
    meter.src = 'meter.png';
    needle.src = 'needle.png';
}   

However I want to move the needle slowly to the degree which I entered such as speedtest webpages. Any idea? Thanks.

like image 274
user1874941 Avatar asked Dec 19 '12 08:12

user1874941


1 Answers

Something like this should work:

var meter = new Image,
    needle = new Image;
window.onload = function () {
    var c = document.getElementsByTagName('canvas')[0],
        ctx = c.getContext('2d'),
        x,        // Current angle
        xTarget,  // Target angle.
        step = 1; // Angle change step size.

    setInterval(function () {
        if(Math.abs(xTarget - x) < step){
            x = xTarget; // If x is closer to xTarget than the step size, set x to xTarget.
        }else{
            x += (xTarget > x) ?  step : // Increment x to approach the target.
                 (xTarget < x) ? -step : // (Or substract 1)
                                  0;
        }
        ctx.save();
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.translate(c.width / 2, c.height / 2);
        ctx.drawImage(meter, -165, -160);
        ctx.rotate((x * Math.PI / 180); // x degree  
            ctx.drawImage( needle, -13, -121.5 );
            ctx.restore();
        },50);
    };
    dial.src = 'meter.png';
    needle.src = 'needle.png';
}

I'm using a shorthand if / else here to determine whether to add 1 to x, substract 1, or do nothing. Functionally, this is the same as:

if(xTarget > x){
    x += step;
}else if(xTarget < x){
    x += -step;
}else{
    x += 0;
}

But it's shorter, and in my opinion, just as easy to read, once you know what a shorthand if (ternary operator) looks like.

Please keep in mind that this code assumes x is a integer value (So, not a float, just a rounded int).

like image 112
Cerbrus Avatar answered Sep 29 '22 17:09

Cerbrus