[英]Drag & Drop menu with Draw2D.js
您可以在此處找到此示例的代碼:
這個想法是在鼠標移動之后向 dom 添加一個幽靈 img 並在 drop 事件中創建新元素。
此示例中的以下代碼摘錄正是執行拖放操作所需的:
onMouseDrag:function(canvas, dx, dy, dx2, dy2)
{
var _this = this;
if( !((this.mouseDraggingElement instanceof draw2d.ResizeHandle) || (this.mouseDraggingElement instanceof draw2d.Port))){
if(this.cloneOnDrag ===true && this.mouseDraggingElement !==null){
var tmp = this.mouseDraggingElement;
// get the current position of the selected shape
// cancel the current drag&drop operation
var pos = this.mouseDraggingElement.getPosition();
this.mouseDraggingElement.onDragEnd(pos.x, pos.y, false,false);
this.mouseDraggingElement = null;
// PNG snapshot's didn'T work with all kind of shapes. You can use
// a DIV ghost as workaround if this didn't work for you
//
var usePNGSnapshot = true;
// create an base64 coded image snapshoot from the figure
// (not from the complete canvas)
//
if(usePNGSnapshot===true) {
new draw2d.io.png.Writer().marshal(tmp, function (base64Image) {
// add the image to the DOM tree
//
var ghost = $("<img style='position:absolute'>");
ghost.attr("src", base64Image);
_this.setupDragDropGhost(tmp, ghost);
});
}
else{
var ghost = $("<div>");
ghost.css({
position: "absolute",
width: tmp.getWidth(),
height: tmp.getHeight(),
border:"1px dotted black",
borderRadius:"3",
backgroundColor:"rgba(128,128,200,0.3)"
});
_this.setupDragDropGhost(tmp, ghost);
}
}
}
this.cloneOnDrag=false;
this._super(canvas, dx,dy,dx2,dy2);
},
setupDragDropGhost: function(figure, ghost){
var _this = this;
$("body").append(ghost);
// and track mouseMove events to move the IMG element around
//
var offset = _this.mouseDownPos.subtract(figure.getPosition());
var mousemoveHandler = function (e) {
var diffX = e.pageX - offset.x;
var diffY = e.pageY - offset.y;
ghost.css('left', diffX + 'px').css('top', diffY + 'px');
};
$(document).bind('mousemove', mousemoveHandler);
ghost.bind('mouseup', function (e) {
try {
// this is a drop event...determine the related canvas and add
// the figure clone to the canvas
//
$(document).unbind('mousemove', mousemoveHandler);
var r1 = new draw2d.geo.Rectangle($("#container1")[0].getBoundingClientRect());
var r2 = new draw2d.geo.Rectangle($("#container2")[0].getBoundingClientRect());
var canvas1Hit = r1.hitTest(e.pageX, e.pageY);
var canvas2Hit = r2.hitTest(e.pageX, e.pageY);
if (canvas1Hit) {
var clone = figure.clone();
var p = canvas1.fromDocumentToCanvasCoordinate(e.pageX, e.pageY);
clone.setPosition(p.subtract(offset));
canvas1.add(clone);
}
if (canvas2Hit) {
var clone = figure.clone();
var p = canvas2.fromDocumentToCanvasCoordinate(e.pageX, e.pageY);
clone.setPosition(p.subtract(offset));
canvas2.add(clone);
}
}
finally{
ghost.remove();
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.