2014-04-17 77 views
0

我試圖實現的是一個簡單的功能,當點擊鼠標時在畫布上畫線。用鼠標移動畫布,HMTL5?

我看了網上的代碼,並試圖自己實現它,但它不會工作。

到目前爲止:

<html> 
<canvas id="myCanvas" width="400" height="500"> </canvas> 
</html> 

<script type="text/javascript"> 
var el = document.getElementById('myCanvas'); 
    var ctx = el.getContext('2d'); 
    var isDrawing; 

    el.onmousedown = function(e) { 

     isDrawing = true; 
     ctx.moveTo(e.clientX, e.clientY); 
    }; 

    el.onmousemove = function(e) { 
     if (isDrawing) { 
     ctx.lineTo(e.clientX, e.clientY); 
     ctx.stroke(); 
     } 
    }; 
    el.onmouseup = function() { 

     isDrawing = false; 
    }; 

</script> 

這確實然而在畫布上的任何輸出。我並不完全瞭解代碼的事件處理方面(即e.clientX,e.clientY) 我懷疑我必須添加這些代碼才能獲得所需的效果?

+0

它適用於我,您的畫布元素不是封閉順便說一句。 [jsFiddle](http://jsfiddle.net/7huq7/) – Thunda

+0

我錯過了粘貼時,它在我的代碼中,雖然 –

+0

哇,這很奇怪,它在jsFiddle中工作,完全相同的代碼不能在我的實際工作頁。 –

回答

0

呃,匆匆一瞥,你在第2行末尾缺少一個「>」。

0

幾個問題:

  • 由偏移畫布的(除非你的畫布是在左上角的瀏覽器)

  • 調節鼠標位置做鼠標移動的所有繪畫命令(否則你restroke每ctx.stroke行)

這裏的示例代碼和演示:http://jsfiddle.net/m1erickson/kkLrT/

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 
<style> 
    body{ background-color: ivory; } 
    canvas{border:1px solid red;} 
</style> 
<script> 
$(function(){ 

    var canvas=document.getElementById("canvas"); 
    var ctx=canvas.getContext("2d"); 
    var BB=canvas.getBoundingClientRect(); 
    var offsetX=BB.left; 
    var offsetY=BB.top; 

    var lastX,lastY; 
    var isDown=false; 

    canvas.onmousedown=handleMousedown; 
    canvas.onmousemove=handleMousemove; 
    canvas.onmouseup=handleMouseup; 


    function handleMousedown(e){ 
     e.preventDefault(); 
     e.stopPropagation(); 
     lastX=e.clientX-offsetX; 
     lastY=e.clientY-offsetY; 
     isDown=true; 
    } 

    function handleMouseup(e){ 
     e.preventDefault(); 
     e.stopPropagation(); 
     isDown=false; 
    } 

    function handleMousemove(e){ 
     e.preventDefault(); 
     e.stopPropagation(); 

     if(!isDown){return;} 

     var mouseX=e.clientX-offsetX; 
     var mouseY=e.clientY-offsetY; 

     ctx.beginPath(); 
     ctx.moveTo(lastX,lastY); 
     ctx.lineTo(mouseX,mouseY); 
     ctx.stroke(); 

     lastX=mouseX; 
     lastY=mouseY; 
    } 


}); // end $(function(){}); 
</script> 
</head> 
<body> 
    <h4>Drag mouse to draw.</h4> 
    <canvas id="canvas" width=300 height=300></canvas> 
</body> 
</html> 
+0

看起來不錯,但我正在尋找一個純粹的Js解決方案 –

+0

所以只需使用window.onload而不是$(function(){})。我的答案都不需要jQuery; =) – markE