how to remove text from canvas in javascript

2019-08-27 16:34发布

问题:

my problem is that when i am clicking on button, callfunction() method called and counter is incremented by 5, when i am again click counter incremented by 5 and displayed 10 on given location my problem is that when counter is incremented previous number is not erased and displayed incremented number on previous number.I want to remove previous number and display next incremented number. i have following code

var count=0;
function callfunction()
   {
         context.fillText(count,200,200);
         count = count+5;
         //context.fillText("",200,200);
   }

回答1:

fillText with background colour, if it's monochromatic. Or preserve what was there before as image data, then paste it over later when you want to erase the text.



回答2:

The only way i know is to clear the full canvas element using canvas.fillRect.

Please see this jsFiddle for an example.



回答3:

count = 0;
function update(){
    canvas.clearRect(0,0,canvas.width,canvas.height);
    canvas.fillText(count,200,200);
    //Draw anything else...

}

setInterval("update()",1000/60); //60 Frames per second

button.onclick = function(){ //Change button to your button element
    count += 5;
}

This should work!



回答4:

You can use clearRect() to just clear a portion of the canvas...

If you know the size of your text field, set clearRect() to a rectangle large enough to clear that text field:

var count=0;
function callfunction()
   {
    context.clearRect(200, 190, 50, 10); // clears a text field 50 x 10, above baseline
    context.fillText(count,200,200);
    count = count+5; 
   }


回答5:

Try clearing the canvas first:

    var count=0;
    function callfunction()
   {
         context.clearRect ( 0 , 0 ,canvas.height , canvas.width );
         context.fillText(count,200,200);
         count = count+5;
         //context.fillText("",200,200);
   }