2012-12-06 56 views
0

我有一個可以用鼠標繪製的HTML5畫布。我希望能夠清除畫布,以便用戶可以製作新的繪圖。我這樣做:myContext.clearRect(0,0,500,700);不清除畫布正確

myContext.clearRect(0, 0, 500, 700); 

畫布顯示清晰,但只要用戶開始新的繪圖,舊的繪圖會重新出現。我的鼠標繪圖部分JavaScript是:

// Variables 
var x1; 
var y1; 
var isPressed = false; 
var myCanvas; 
var myContext; 

function startCanvas() { 

    // Canvas stuff 
    myCanvas = document.getElementById("can1"); 
    myContext = myCanvas.getContext("2d"); 

    // Specify a black background, and white lines that are 3 pixels thick. 
    myContext.fillStyle = '#000000'; 
    myContext.strokeStyle = '#000000'; 
    myContext.fillRect(0, 0, 500, 700); 
    myContext.lineWidth = 3; 
    myContext.fill(); 
} 

function functionMouseDown(e) { 
    // Get coordinates 
    x1 = e.clientX - myCanvas.offsetLeft; 
    y1 = e.clientY - myCanvas.offsetTop; 

    isPressed = true; 
} 

function functionMouseMove(e) { 
    // If mouse is down and moved start drawing line 
    if (isPressed == true) { 
     drawLine(e); 
    } 
} 

function functionMouseUp() { 
    // Stop drawing line 
    isPressed = false; 
} 

function drawLine(e) { 
    // Draw line 
    var x = e.clientX - myCanvas.offsetLeft; 
    var y = e.clientY - myCanvas.offsetTop; 

    myContext.strokeStyle = '#ffffff'; 
    myContext.lineWidth = 1; 
    myContext.moveTo(x1, y1); 
    myContext.lineTo(x, y); 
    myContext.stroke(); 

    // Set start coordinates to current coordinates 
    x1 = x; 
    y1 = y; 
} 

startCanvas(); 

的HTML是:

<canvas id="can1" width="500" height="700"></canvas> 
+0

你可以提供一個[小提琴](http://jsfiddle.net)? –

回答

2
myContext.strokeStyle = '#000000'; 
myContext.beginPath();//<---- add this and read about this. 
myContext.fillRect(0, 0, 500, 700); 
myContext.lineWidth = 3; //why? 
myContext.fill(); 
+0

這沒有什麼區別。 – user1822824

+0

沒關係,當我添加myContext.beginPath();到固定畫布清除問題的drawLine函數。謝謝! – user1822824