【问题标题】:draggable inside Canvas element可在 Canvas 元素内拖动
【发布时间】:2014-04-10 20:04:37
【问题描述】:

我遇到了画布问题。我实现了一个在 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/

【问题讨论】:

    标签: canvas drag-and-drop


    【解决方案1】:

    Html 画布是一个固定的位图,所以图像本身不能被拖动。 (在画布上绘制的图像成为现有绘图的永久部分)。

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

    第 1 步: 跟踪每个图像对象以及它们需要在画布上的位置

    创建一个数组,其中包含定义图像及其位置的 javascript 对象

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

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

    鼠标按下时:

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

    鼠标移动时:

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

    鼠标上移:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-30
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多