2012-01-04 5 views
0

canvas 요소 주위로 이미지를 드래그하려고합니다. 나는 드래그 작업을 했음에도 불구하고 내가 좋아할만큼 효과가 없습니다.캔버스에 이미지 드래그

기본적으로 이미지는 캔버스 요소보다 항상 크지 만 캔버스 내의 이미지의 왼쪽은 캔버스의 왼쪽보다 더 이상 오른쪽으로 갈 수 없으므로 오른쪽이 마찬가지로 허용되지 않습니다. " 더 오른쪽 "을 캔버스의 오른쪽보다. 기본적으로 이미지는 공백이 표시되지 않도록 제한됩니다. 캔버스 공간.

끌기의 문제는 이미지를 "끌기"시작할 때마다 0,0이 마우스 위치에서 오는 것처럼 돌아가는 것입니다. 실제로는 현재 위치에서 이미지를 이동하려고합니다.

document.onmousemove = function(e) { 
    if(mouseIsDown) { 
     var mouseCoords = getMouseCoords(e); 
     offset_x += ((mouseCoords.x - canvas.offsetLeft) - myNewX); 
     offset_y += ((mouseCoords.y - canvas.offsetTop) - myNewY); 

     draw(offset_x, offset_y); 

     // offset_x = ((mouseCoords.x - canvas.offsetLeft) - myNewX); 
     // offset_y = ((mouseCoords.y - canvas.offsetTop) - myNewY); 

     // offset_x = (mouseCoords.x - canvas.offsetLeft) - myNewX; 
     // offset_y = (mouseCoords.y - canvas.offsetTop) - myNewY; 

     offset_x = prevX; 
     offset_y = prevY; 
    } 

    /*if(mouseIsDown) { 
     var mouseCoords = getMouseCoords(e); 
     var tX = (mouseCoords.x - canvas.offsetLeft); 
     var tY = (mouseCoords.y - canvas.offsetTop); 

     var deltaX = tX - prevX; 
     var deltaY = tY - prevY; 

     x += deltaX; 
     y += deltaY; 

     prevX = x; 
     prevY = y; 

     draw(x, y); 
    }*/ 
}; 

지금 내가 가지고있는 것, 나는 평행 효과를 얻습니다.

+0

을이 치료해야합니까? 그렇지 않다면 plz는 전체 코드를 jsfiddle.net 또는 적어도 최소한의 예제로 작성합니다. – puk

+0

주석 처리 된 코드가있는 이유는 무엇입니까? 다른 사람을 혼동하지 않도록 그걸 제거해야합니다. 또한, myNewX/myNewY는 무엇입니까? – puk

답변

0

이동 될 때 이미지의 현재 오프셋을 기록하고 초기 오프셋을 결정하기 위해 각 이미지와 함께 이미지의 현재 오프셋을 기록하고 캔버스의 왼쪽 상단에서 오프셋과 함께 사용해야합니다.

var dragging = false, 
    imageOffset = { 
     x: 0, 
     y: 0 
    }, 
    mousePosition; 

function dragImage(coords) { 
    imageOffset.x += mousePosition.x - coords.x; 
    imageOffset.y += mousePosition.y - coords.y; 

    // constrain coordinates to keep the image visible in the canvas 
    imageOffset.x = Math.min(0, Math.max(imageOffset.x, canvas.width - imageWidth)); 
    imageOffset.y = Math.min(0, Math.max(imageOffset.y, canvas.height - imageHeight)); 

    mousePosition = coords; 
} 

function drawImage() { 
    // draw at the position recorded in imageOffset 
    // don't forget to clear the canvas before drawing 
} 

function getMouseCoords(e) { 
    // return the position of the mouse relative to the top left of the canvas 
} 

canvas.onmousedown = function(e) { 
    dragging = true; 
    mousePosition = getMouseCoords(e); 
}; 
document.onmouseup = function() { 
    dragging = false; 
}; 
document.onmousemove = function(e) { 
    if(dragging) dragImage(getMouseCoords(e)); 
}; 
내가 어떤 방법으로 그것을 테스트하지 않았습니다 나는이 jsfiddle로이이 동작을 재현한다 붙여 복사하는 경우

당신은 아마 ... 의사로 ;-)