可拖动的Canvas元素

时间:2014-03-07 15:25:38

标签: canvas drag-and-drop

我遇到了画布的问题。我实现了一个解决方案,将图像拖放到Canvas元素(实际上是一个网格)中。一旦图像被丢弃,就无法重新拖动,这限制了解决方案的灵活性。我错过了一条线吗?

function dragDrop(e,ui){

    // get the drop point (be sure to adjust for border)
    var x=parseInt(ui.offset.left-offsetX)-1;
    var y=parseInt(ui.offset.top-offsetY);

    // get the drop payload (here the payload is the $tools index)
    var theIndex=ui.draggable.data("toolsIndex");

    // drawImage at the drop point using the dropped image 
    ctx.drawImage($tools[theIndex],x,y,32,32);

}

我提到了这个演示:http://jsfiddle.net/m1erickson/cyur7/

1 个答案:

答案 0 :(得分:2)

Html画布是固定的位图,因此无法原生拖动图像。 (在画布上绘制的图像成为现有图形的永久部分)。

要使图像在画布上可拖动,您必须重新绘制所有画布,并将“拖动”图像移动到新的所需位置。

第1步: 跟踪每个图像对象及其在画布上的位置

创建一个填充了定义图像及其位置的javascript对象的数组

var images=[];

images.push({
    x:100,
    y:100,
    width:yourImageElement.width,
    height:yourImageElement.height,
    image:yourImageElement
});

步骤2: 监听鼠标事件并根据这些事件创建拖动系统

关于mousedown:

  • 遍历图像数组中的每个图像。
  • 测试每个图像以查看鼠标是否在该图像上方(参见下面的命中测试示例)。
  • 在变量中保存对“命中”图像的引用:var selected = images [hitIndex]
  • 如果鼠标位于图像上方,请设置isDragging标志:var isDragging = true;

关于mousemove:

  • 计算自上次mousemove事件以来鼠标移动的距离
  • 将该距离添加到所选图像的x,y
  • 重绘画布上的所有内容
  • 因为你改变了“拖动”图像的x,y,它似乎已经移动了!
  • 每次鼠标移动重复

关于mouseup:

  • 清除isDragging标志,因为拖动结束且图像已重新定位

命中测试示例:鼠标悬停在图像上吗?

var thisImageIsUnderMouse=(
    mouseX>=image.x 
    && mouseX<=image.x+image.width
    && mouseY>=image.y
    && mouseY<=image.y+image.height
)