Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  54] [ 5]  / answers: 1 / hits: 24131  / 14 Years ago, sun, december 26, 2010, 12:00:00

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


More From » canvas

 Answers
17

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.


[#94491] Wednesday, December 22, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
ryanulyssesb questions
Sat, Mar 20, 21, 00:00, 3 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
Sun, Jul 7, 19, 00:00, 5 Years ago
;