2017-03-12 44 views
1

我有這個JavaScript代碼,當我點擊按鈕,畫布清理。HTML5乾淨的畫布與按鈕

但是,當我移動鼠標,在畫布上顯示我什麼我以前寫的,它不以空白畫布開始

我能做些什麼來開始一個空白的畫布後,我按一下按鈕?

謝謝。

<!DOCTYPE html> 
<html> 
<body> 

    <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"> 
    Your browser does not support the HTML5 canvas tag.</canvas> 
    <div id="buttons"> 
     <input type="button" id="clear" value="Clear"> 
     <input type="button" onClick="erase()" value="Erase"> 
    </div> 



    <script> 
    var canvas = document.getElementById("myCanvas"); 
    var ctx = canvas.getContext("2d"); 

     function getMousePos(canvas, evt) { 
     var rect = canvas.getBoundingClientRect(); 
     return { 
      x: evt.clientX - rect.left, 
      y: evt.clientY - rect.top 
     }; 
     } 

     canvas.addEventListener('mousemove', 
           function(evt){ 
            var mousePos = getMousePos(canvas, evt); 
            ctx.clearRect(0, 0, canvas.width, canvas.height); 
            ctx.strokeStyle = 'red'; 
            ctx.lineTo(mousePos.x,mousePos.y); 
            ctx.stroke(); 
           } 

    ); 

     document.getElementById('clear').addEventListener('click', function(){ 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
     }, false); 


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

    </script> 

</body> 
</html> 
+1

在** **開發工具控制檯任何錯誤?即關於'context'是未定義的? –

+0

是的:D分心......我注意到並糾正了我的問題。謝謝:)但現在我有另一個問題了:當我移動鼠標時,畫布顯示我之前寫過的內容,而不是以空白畫布開始。我怎麼做才能開始與空白畫布後,我點擊按鈕? – andrea

回答

2

記住使用beginPath()也清楚這劇照clearRect()已使用後存在的路徑,例如:

function(evt){ 
    var mousePos = getMousePos(canvas, evt); 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    ctx.strokeStyle = 'red'; 

    ctx.beginPath();  // <- here 
    //ctx.moveTo(x, y); // you will probably also want this at some point 

    ctx.lineTo(mousePos.x,mousePos.y); 
    ctx.stroke(); 
} 
+0

謝謝!它現在有效:D – andrea