2011-12-21 6 views
0

HTML5 캔버스로 그리기 응용 프로그램을 만들고 있습니다. 그것은 하나의 것을 받아들입니다. 드로잉은 커서에서 ~ 50px 아래/오른쪽처럼 발생합니다. 아래 코드는 내 코드입니다. 왜 이런 일이 일어나는지 말할 수 있습니까?캔버스로 그리기가 커서를 따라 가지 않습니다.

var letsdraw = false; 

var theCanvas = document.getElementById('paint'); 
var ctx = theCanvas.getContext('2d'); 
theCanvas.width = 420; 
theCanvas.height = 300; 


$('#paint').mousemove(function(e) { 
    if (letsdraw === true){ 
     ctx.strokeStyle = 'blue'; 
     ctx.lineWidth = 100; 
     ctx.lineCap = 'round'; 
     ctx.beginPath(); 
     ctx.moveTo(e.pageX, e.pageY); 
     ctx.lineTo(e.pageX, e.pageY);   
     ctx.stroke(); 
    } 
}); 

$('#paint').mousedown(function(){ 
    letsdraw = true; 
}); 

$('#paint').mouseup(function(){ 
    letsdraw = false; 
}); 

답변

4

몇 가지 항목이 있습니다. 첫째, 핵심 문제에 대해서는 pageX와 pageY 만보고 있지만 캔버스의 오프셋을 고려하지는 않습니다. 따라서 캔버스가 페이지에서 50 픽셀 아래로 오면 잘못된 위치에 그림을 그려야합니다.

또한 유효한 문법이 아니므로 mousemove에서 moveTo와 lineTo를 모두 사용하지 않으셔도됩니다. . 당신은 기본적으로 (x, y)를 가리킨에서 선 (X, Y)를 그려 "라고하고 여기에 대한 코드의 업데이트 비트, 당신은 여기에 대한 jsfiddle을 찾을 수 있습니다 : http://jsfiddle.net/fordlover49/wPx4d/

$(function() { 
    var letsdraw = false; 

    var theCanvas = document.getElementById('paint'); 
    var ctx = theCanvas.getContext('2d'); 
    theCanvas.width = 420; 
    theCanvas.height = 300; 

    var canvasOffset = $('#paint').offset(); 

    $('#paint').mousemove(function(e) { 
     if (letsdraw === true) { 
      ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top); 
      ctx.stroke(); 
     } 
    }); 

    $('#paint').mousedown(function() { 
     // setup all of the properties for your line on mousedown, not mousemove 
     letsdraw = true; 
     ctx.strokeStyle = 'blue'; 
     ctx.lineWidth = 10; 
     ctx.lineCap = 'round'; 
     ctx.beginPath(); 
     ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top); 
    }); 

    $(window).mouseup(function() { 
     // bind to the window mouse up, that way if you mouse up and you're not over 
     // the canvas you'll still get the release of the drawing. 
     letsdraw = false; 
    }); 
}); 
+0

답변 주셔서 감사합니다, 매력처럼 작동합니다! – holyredbeard

2

정확한 마우스 위치를 얻으려면 계산이 필요합니다. 나는 어떤 다른 방법이 있는지 모르겠지만, 이것은 일반적으로 문제를 해결해야

var mp = getMousePoint(e.pageX, e.pageY); 
    ctx.moveTo(mp.x, mp.y); 
    ctx.lineTo(mp.x, mp.y); 

이를 그릴 점을 얻기 위해

function getMousePoint(ex, ey){ 

    var px = 0, py = 0; 
    var el = document.getElementById('paint'); 
    while (el) { 
     px += el.offsetLeft; 
     py += el.offsetTop; 
     el = el.offsetParent; 
    } 

    return {x: ex-px ,y: ey-py}; 
} 

사용이 기능을 사용하는 것입니다.

+0

이 기능을 모든 브라우저에서 테스트 해 보셨습니까? ** moveTo ** 및 ** lineTo **를 동일한 x, y 점으로 연속적으로 호출하는 것이 일부 브라우저에서는 작동하지 않기 때문에 묻습니다. mousedown 이벤트가 발생했을 때 ** moveTo **를 호출하고 mousemove에서 ** lineTo ** 만 호출하면 더 좋을 것입니다. – Diode

+0

답변 해 주셔서 감사합니다! 브라우저 호환성 부족에 대해 옳았습니다. Firefox에서 작동했지만 Chrome에서는 작동하지 않았습니다. 내가 제안한 변경 사항은 물론 기능을 구현했지만 지금은 그릴 때 아무 일도 일어나지 않습니다. 원하는 경우 시간이, 새로운 코드는 여기에 (어쩌면 나는 뭔가 잘못한 짓을했습니다) : http://jsfiddle.net/bXC39/ – holyredbeard

0

당신 캔버스의 offsetLeftoffsetTop을 각각 X 좌표와 Y 좌표에서 빼서 정확한 마우스 좌표를 얻을 수 있습니다. 또 다른 메모에서는 ms 페인트 또는 포토샵에서 마우스를 움직여서 그리는 경우를 상상해보십시오. 당신은 마우스 버튼을 눌렀을 것입니다. 어쨌든 그리는 것입니다. 짜증나고 직관적이지 않습니까? 대신 마우스 이벤트에서 관련 데이터를 가져 와서 일정 기간 동안 확인하십시오.

운 좋게도, 이런 종류의 물건은 jQueryprototype과 같은 라이브러리를 만들 정도로 간단하며 "원시"JavaScript로 수행 할 수 있습니다.

여기 예를 들어, 나의 꽝입니다 :

var mouse = [0,0], mouseDown = false, last = [0,0], fps = 24 
ctx = canvas.getContext('2d'); 
getMouse = function(e){ 
    var X,Y; 
    X = e.pageX || e.clientX || e.offsetX; 
    Y = e.pageY || e.clientY || e.offsetY; 
    X = X - canvas.offsetLeft; 
    Y = Y - canvas.offsetTop; 
    mouse = [X,Y]; 
} 
canvas.onmousedown = function(e){ 
    getMouse(e); 
    mouseDown = true; 
    last = mouse; 
} 
canvas.onmouseup = function(){ 
    mouseDown = false; 
} 
canvas.onmousemove = getMouse; 
setInterval(function(){ 
    if(mouseDown){ 
     ctx.beginPath(); 
     ctx.moveTo(last[0],last[1]); 
     ctx.lineTo(mouse[0],mouse[1]); 
     ctx.stroke(); 
     ctx.closePath(); 
     last = mouse; 
    } 
},1000/fps); 

당신은 행동 here에서 볼 수 있습니다. 그리려면 클릭하고 드래그하십시오.


도움이되기를 바랍니다.

+0

'fps' 변수를 늘리면보다 정확하고 들쭉날쭉 한 선이 생깁니다. –

관련 문제