Canvas 可拖动的内部画布元素
我面临画布的问题。我实现了一个在画布元素(实际上是网格)中拖放图像的解决方案。一旦图像被删除,就无法重新拖动,这限制了解决方案的灵活性。我漏了一行吗Canvas 可拖动的内部画布元素,canvas,drag-and-drop,Canvas,Drag And Drop,我面临画布的问题。我实现了一个在画布元素(实际上是网格)中拖放图像的解决方案。一旦图像被删除,就无法重新拖动,这限制了解决方案的灵活性。我漏了一行吗 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);
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);
}
我提到了这个演示:Html画布是一个固定的位图,所以图像不能以本机方式拖动。(在画布上绘制的图像将成为现有图形的永久部分) 要使图像可在画布上拖动,必须将“拖动”的图像移动到新的所需位置,然后重新绘制所有画布 步骤#1:跟踪每一个图像对象以及它们在画布上的位置 创建一个包含javascript对象的数组,用于定义图像及其位置
var images=[];
images.push({
x:100,
y:100,
width:yourImageElement.width,
height:yourImageElement.height,
image:yourImageElement
});
步骤#2:侦听鼠标事件并基于这些事件创建拖动系统
在mousedown:
- 遍历图像数组中的每个图像
- 测试每个图像以查看鼠标是否在该图像上(请参见下面的命中测试示例)
- 将对“命中”图像的引用保存在变量中:var selected=images[hitdex]
- 如果鼠标位于图像上方,则设置IsDraging标志:var isDraging=true李>
- 计算自上次mousemove事件以来鼠标移动的距离
- 将该距离添加到选定图像的x,y
- 重新绘制画布上的所有内容
- 由于您更改了“拖动”图像的x、y,因此它似乎已移动李>
- 每次鼠标移动时重复
- 清除IsDraging标志,因为拖动已结束且图像已重新定位
var thisImageIsUnderMouse=(
mouseX>=image.x
&& mouseX<=image.x+image.width
&& mouseY>=image.y
&& mouseY<=image.y+image.height
)
var thismageisundermouse=(
mouseX>=image.x
&&mouseX=image.y
&&老鼠