How to remove an object from the canvas?
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,
MariusUse 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.
Simple answer: Redraw the canvas with right angle.
Use context.clearRect() or set the canvas width to the same value (changing it to whatever value will clear the canvas);
It's fast and there is no way to move just the needle. All canvas stuff are build that way.
Draw. Change? Redraw.
As you are using a static background image and only the needle is dynamic you could simply use multiple canvases. Position them on top of each other using css. Add the tachometer image to the canvas in the back. Apply the needle script to the top canvas. This way you don't have to redraw the image everytime you update the needle. And as the other answers explain redraw means clear context and draw needle again.
精彩评论