How to remove an object from the canvas?

I am doing this script that will rotate the needle on the tachometer using a canvas. I am new 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 action in action:

http://www.kingoslo.com/instruments/

The problem is that the red needle is not removed between each loop.

What I need to do is clear the canvas for the pin object between each cycle of the loop. How to do it?

Thanks.

Yours faithfully,
Marius

+4
source share
3 answers

Use clearRect to clear the canvas (or parts of it, or all of this). An HTML canvas object is just a flat bitmap of pixels, so there is no concept of “objects” on the canvas.

Also keep in mind that JavaScript is single-threaded, so the for loop will not animate the needle, it just sits and draws all updates, after which the browser will actually update the visible canvas with the last state.

If you want to revive it, you will have to create a rendering cycle. Dev.Opera has an article on frame rate management that should get you started, then you just need to animate your needle on every frame.

+7
source

The simple answer is to drag the canvas at right angles.

Use context.clearRect () or set the width of the canvas to one value (changing it to any value that clears the canvas);

It is fast, and there is no way to move only the needle. All canvas materials are constructed in this way.

Draw. Change? Redrawing.

+2
source

When you use a static background image, and only the needle is dynamic, you can just use a few canvases. Lay them on top of each other using css. Add a tachometer image to the canvas on the back. Put the needle script on the top canvas. Thus, you do not need to redraw the image every time you update the needle. And how do the other answers explain that redrawing means a clear context and drawing the needle again.

+1
source

Source: https://habr.com/ru/post/1333432/


All Articles