在画布上拖动图像

时间:2012-01-04 09:43:45

标签: image canvas drag

我试图在canvas元素周围拖动图像。虽然我已经拖延工作了,但它并没有像我一样的工作。

基本上,图像总是比画布元素大,但画布中图像的左侧不能比画布的左侧更靠右,同样右侧不允许去# 34;更正确"而不是画布的右侧。基本上,图像被限制为不显示任何空白画布空间。

拖动的问题在于,每当我开始拖动图像时,弹出"弹出"返回以表示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);
    }*/
};

我现在拥有的是什么,我得到了一种并行效果。

1 个答案:

答案 0 :(得分: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));
};

您应该将此视为伪代码,因为我没有以任何方式对其进行测试...; - )