2012-10-19 124 views
1

嗨我正在做一个绘图应用程序使用画布,但我不知道如何清除画布。 我试过clearRect和其他功能,但他们不工作。 脚本的最后两个函数应清除画布,但他们没有工作... (对不起我的英文不好) 下面的代码:如何清除画布?

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

可能重复[如何清除重绘帆布(http://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing) – Prestaul

回答

4

需要更多的代码真正看到了什么问题是。这是真的简单,你可以去或许缩小范围。出于性能原因,最好使用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); 

0

你检查你是否清除正确的印刷品吗?也许如果你向我们提供更多的代码,我们可以进一步帮助你。

另外,请确保在清除之后不要拖过它。

但是,说到清理画布,这是我知道的最简单的方法。

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

但你也可以使用

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

从;

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