I am making this script that will rotate a needle on a tachometer using canvas. I am a newbie to this canvas. This is my code:
function startup() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var meter = new Image();
meter.src = 'background.png';
var pin = new Image();
pin.src = 'needle.png';
context.drawImage(meter,0,0);
context.translate(275,297);
for (var frm = 0; frm < 6000; frm++){
var r=frm/1000; //handle here
var i=r*36-27; //angle of rotation from value of r and span
var angleInRadians = 3.14159265 * i/180; //converting degree to radian
context.rotate(angleInRadians); //rotating by angle
context.drawImage(pin,-250,-3); //adjusting pin center at meter center
}
}
Here is the script in action:
http://www.kingoslo.com/instruments/
The problem is, as you can see, that the red needle is not removed beetween each for-loop.
What I need to do is to clear the canvas for the pin object between each cycle of the loop. How do I do this?
Thanks.
Kind regards,
Marius
Use clearRect to clear the canvas (either parts of it or the whole thing). An HTML canvas
object is just a flat bitmap of pixels, so there is no notion of "objects" on the canvas.
Also keep in mind that JavaScript is single threaded, so your for loop will not animate the needle, it will just sit there and draw all the updates, after it's done the browser will actually refresh the visible canvas with its latest state.
If you want to animate it you will have to create a rendering loop. Dev.Opera has an article about framerate control, that should get you started, then you just need to animate your needle on each frame.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With