简体   繁体   English

我怎样才能清除画布?

[英]How can I clear canvas?

Hi I'm doing a drawing app using canvas but i dunno how to clear canvas. 嗨,我正在使用画布做绘图应用程序,但我不知道如何清除画布。 I've tried clearRect and other functions but they don't work. 我尝试过clearRect和其他功能,但它们不起作用。 The last two function of the script should clear canvas but they don't work... (sorry for my bad english) Here the code: 脚本的最后两个功能应该清除画布,但它们不起作用...(抱歉我的英文不好)这里的代码:

  function clear_canvas_width ()
      {
            var s = document.getElementById ("scribbler");
            var w = s.width;
            s.width = 10;
            s.width = w;
        }

        function clear_canvas_rectangle ()
        {
               var canvas = $('#canvas')[0]; // or document.getElementById('canvas');
               canvas.width = canvas.width;
         }

Need a bit more code to really see what the problem is. 需要更多代码才能真正了解问题所在。 Here is something really simple that you can go off of to maybe narrow it down. 这里有一些非常简单的东西可以让你缩小范围。 Also for performance reasons its better to use clearRect over resetting the width of the canvas. 同样出于性能原因,最好使用clearRect不是重置画布的宽度。 How you clear your canvas matters 如何清理画布很重要

Live Demo 现场演示

var clearBut = document.getElementById("clearCan"),
    canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");


canvas.width = canvas.height = 300;
ctx.fillRect(10,10,280,280);


function clearCanvas(){
    ctx.clearRect(0,0,canvas.width, canvas.height);        
}

clearBut.addEventListener("click", clearCanvas);

Have you checked whether you are clearing the right canvas? 你有没有检查过你是否正在清理合适的画布? Maybe if you provide us with more code we can help you further. 也许如果您向我们提供更多代码,我们可以为您提供更多帮助。

Also make sure you don't draw over it after you have cleared it. 还要确保在清除它之后不要覆盖它。

However, when it comes to clearing canvases this is the easiest way I know. 然而,当谈到清理画布时,这是我所知道的最简单的方法。

function clear_canvas( canvas ){
    canvas.width = canvas.width;
}

But you can also use 但你也可以使用

function clear_canvas (ctx, canvas){
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
}

from; 从;

How to clear the canvas for redrawing 如何清除画布以进行重绘

// Store the current transformation matrix
ctx.save();

// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);

// Restore the transform
ctx.restore();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM