2017-05-13 5 views
1

마우스 끌기 좌표를 가져 오려고합니다. 나는 새로운 마우스 (픽셀)의 좌표를 가져오고 싶다면 캔버스가 있고 그 안에 내가 동일한 객체를 그립니다. 내 코드는 자바 스크립트에 있습니다. 내 개체가 html의 태그 elemnts에 픽셀이있는 캔버스 안에 그림이 그려져 있으며 마우스로 그 사람을 붙잡고 마우스의 새로운 조정이 필요합니다.마우스 드래그 좌표 받기

감사합니다,

답변

1

캔버스 2D 이미지 요소/태그의 일종이다, 그래서 캔버스 내부의 개체를 끌어 직접적인 방법이 없습니다.

캔버스 내부에서 마우스 이벤트를 수신하고 이러한 이벤트를 기반으로 캔버스를 다시 칠해야합니다.
캔버스

내부의 의견에 대한
function handleMouseDown(e) { 
    var mousePos = getMousePosition(canvas, e); 
    // if current position matches the object postion 
    // set a flag and monitor mouse move and mouse up event 
} 
function handleMouseUp(e) { 
    var mousePos = getMousePosition(canvas, e); 
    //if your flag is true, then move the object to here and reset flag 
} 
function handleMouseMove(e) { 
    var mousePos = getMousePosition(canvas, e); 
    //Handle if you need smooth drag experience 
} 
function getMousePosition(canvas, e) { 
    var boundary = canvas.getBoundingClientRect(); 
    // (e.clientX, e.clientY) => Mouse coordinates wrt whole browser 
    // (boundary.left, boundary.top) => Canvas starting coordinate 
    return { 
     x: e.clientX - boundary.left, 
     y: e.clientY - boundary.top 
    }; 
} 
var canvas = document.getElementById('canvasId'); 
canvas.addEventListener('mousemove', handleMouseMove, false); 
canvas.addEventListener('mousedown', handleMouseDown, false); 
canvas.addEventListener('mouseup', handleMouseUp, false);  
+0

덕분에 개체를 끌어 이러한 3 개 이벤트를 청취하지만이 시도하고 나는이 값 e.clientX 인쇄 할 때 콘솔 NAN 얻을 - boundary.left, e.clientY을 - boundary.top – adi

+0

@adi 대답을 업데이트했습니다. 시도해보십시오. – Ajay

+0

감사합니다. – adi