2012-01-04 51 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

如果我複製粘貼到的jsfiddle將它重新的行爲?如果沒有,請將完整的代碼放在jsfiddle.net上,或者至少是一個簡單的例子。 – puk 2012-01-05 00:05:15

+0

爲什麼你有被註釋掉的代碼?你應該刪除它,不要混淆任何人。另外,什麼是myNewX/myNewY? – puk 2012-01-05 00:08:51

回答

0

您必須在圖像移動時記錄圖像的當前偏移量,並將每個mousedown的圖像(除了畫布左上角的偏移量)用於確定初始偏移量。

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)); 
}; 

你或許應該將此視爲僞因爲我沒有以任何方式測試了它... ;-)