2012-10-19 170 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();