【问题标题】:Drag image on canvas在画布上拖动图像
【发布时间】:2012-01-04 09:43:45
【问题描述】:

我正在尝试围绕canvas 元素拖动图像。虽然我一直拖着工作,但它并没有像我想要的那样工作。

基本上,图像总是比canvas元素大,但是canvas内的图像左侧不能比canvas的左侧更右边,同样右侧也不允许“more”右”而不是画布的右侧。基本上,图像被限制为不显示任何 blank 画布空间。

拖动的问题在于,每当我开始拖动图像时,图像“弹出”回来,就好像 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);
    }*/
};

这就是我现在所拥有的,我有点平行效应。

【问题讨论】:

  • 如果我将其复制粘贴到 jsfiddle 中,它会重新创建行为吗?如果没有,请将完整的代码放在 jsfiddle.net 上,或者至少是一个最小的例子。
  • 为什么有被注释掉的代码?您应该删除它以免混淆任何人。另外,什么是 myNewX/myNewY?

标签: image canvas drag


【解决方案1】:

您必须记录图像移动时的当前偏移量,并在每次鼠标按下时使用该偏移量(除了画布左上角的偏移量)来确定您的初始偏移量。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2022-10-07
    • 2017-09-03
    相关资源
    最近更新 更多