How to slowly move the canvas speedometer needle?

I use the following codes to move the image to the 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 slowly move the needle to the extent that I entered, for example, on pages with quick settings. Any ideas? Thanks.

+7
source share
1 answer

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 use the abbreviated if / else here to determine whether to add 1 to x , subtract 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 is shorter and, in my opinion, as easy to read as you know what the abbreviation if ( ternary operator ) looks like.

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

+7
source

All Articles