2012-12-02 8 views
0

HTML5 캔버스를 사용하는 매우 간단한 JavaScript를 작성했습니다. 사용자가 캔버스에서 마우스를 클릭하면 스크립트는 마우스 좌표를 가져오고 마우스를 움직이면 마우스를 움직여서 선을 그립니다. 마우스를 놓을 때까지 반복됩니다. 하지만 효과가 없으며 왜 그런지 모르겠습니다. 귀하의 도움에 미리 감사드립니다.JavaScript - Canvas Drawing - 스크립트가 작동하지 않습니다.

<body> 
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;"> 
</canvas> 

<script> 
// Canvas link 
var canvas = document.getElementById('myCanvas'); 
var context = canvas.getContext('2d'); 

// Variables 
var x1; 
var y2; 
var isPressed = false; 

// Event listeners 
context.addEventListener('mousedown', functionMouseDown, false); 
context.addEventListener('mousemove', functionMouseMove, false); 
context.addEventListener('mouseup', functionMouseUp, false); 


function functionMouseDown() { 
    // Get coordinates 
    x1 = mousePos.x; 
    y1 = mousePos.y; 

    isPressed = true; 
} 

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

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

function drawLine() { 
// Draw line 
context.moveTo(x1,y1); 
context.lineTo(x,y); 
context.stroke(); 

// Set start coordinates to current coordinates 
x1 = x; 
y1 = y; 
} 
</script> 
</body> 
</html> 
+2

여기서 x와 y는 무엇입니까? – numbers1311407

+1

'mousePos.x/y'와'x/y'는 무엇입니까? –

+0

ActionScript로 시작하여 JavaScript로 변환하는 데 지쳐있었습니다. – user1822824

답변

3

여기에 몇 가지 문제가 있습니다. mousePos.x/y에 단순히 저장되지 않은 마우스 위치를 가져와야합니다. 마우스 이동 이벤트를 통해 mousemove, mousedown, mouseup에 대한 리스너로 추가 된 함수에 첫 번째 매개 변수로 전달됩니다. 다음은 어떻게 수정 했는가입니다.

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

     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; 
    var y = e.clientY; 
    context.moveTo(x1,y1); 
    context.lineTo(x,y); 
    context.stroke(); 

    // Set start coordinates to current coordinates 
    x1 = x; 
    y1 = y; 
    } 
관련 문제