javascript 如何在Javascript中从画布中删除文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10631002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:30:41  来源:igfitidea点击:

How to remove text from canvas in Javascript

javascriptjqueryhtml5-canvas

提问by pravin

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:

我的问题是,当我单击按钮时,callfunction()调用的方法和计数器增加 5,当我再次单击计数器增加 5 并在给定位置显示 10 我的问题是,当计数器增加时,前一个数字不会被删除和显示在前一个数字上增加数字。我想删除前一个数字并显示下一个递增的数字。我有以下代码:

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

采纳答案by Amadan

fillTextwith 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.

fillText带有背景颜色,如果它是单色的。或者将之前的内容保留为图像数据,然后在您想要删除文本时将其粘贴。

回答by GodLesZ

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

我知道的唯一方法是使用canvas.fillRect.

Please see this jsFiddlefor an example.

请参阅此jsFiddle的示例。

回答by Narayan

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!

这应该有效!

回答by Joe's Ideas

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

您可以使用 clearRect() 来清除画布的一部分...

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

如果您知道文本字段的大小,请将 clearRect() 设置为足够大的矩形以清除该文本字段:

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; 
   }

回答by int2000

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);
   }