Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
Marius

like image 943
Mikkel Rev Avatar asked Dec 28 '22 03:12

Mikkel Rev


1 Answers

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.

like image 63
Ivo Wetzel Avatar answered Jan 07 '23 23:01

Ivo Wetzel