我尝试使用SVG在Dart中创建拖放行为。我有BasicUnit
s基本上是GElement
(<g>
)s。现在它有一个body
,这是一个RectElement
。我正在使用该元素来移动单位。这里是定义:Dart SVG Drag and Drop滑动鼠标
class BasicUnit {
SvgSvgElement canvas;
GElement group;
RectElement body;
bool dragging;
num dragOffsetX, dragOffsetY, width, height;
BasicUnit(SvgSvgElement this.canvas, num x, num y, num this.width, num this.height) {
this.body = new RectElement();
this.body.setAttribute('x', '$x');
this.body.setAttribute('y', '$y');
this.body.setAttribute('width', '$width');
this.body.setAttribute('height', '$height');
this.body.classes.add('processing_body');
this.body.onMouseDown.listen(select);
this.body.onMouseMove.listen(moveStarted);
this.body.onMouseUp.listen(moveCompleted);
this.body.onMouseLeave.listen(moveCompleted);
this.group = new GElement();
this.group.append(this.body);
this.dragging = false;
}
void select(MouseEvent e) {
e.preventDefault();
this.dragging = true;
var mouseCoordinates = getMouseCoordinates(e);
this.dragOffsetX = mouseCoordinates['x'] - body.getCtm().e; //double.parse(body.attributes['x']);
this.dragOffsetY = mouseCoordinates['y'] - body.getCtm().f;
}
void moveStarted(MouseEvent e) {
e.preventDefault();
if (dragging) {
var mouseCoordinates = getMouseCoordinates(e);
num newX = mouseCoordinates['x'] - dragOffsetX;
num newY = mouseCoordinates['y'] - dragOffsetY;
this.body.setAttribute('transform', 'translate($newX, $newY)');
}
}
void moveCompleted(MouseEvent e) {
e.preventDefault();
this.dragging = false;
}
dynamic getMouseCoordinates(e) {
return {'x': (e.offset.x - this.canvas.currentTranslate.x)/this.canvas.currentScale,
'y': (e.offset.y - this.canvas.currentTranslate.y)/this.canvas.currentScale};
}
}
我有一个Application
对象。对于给定的id
,它得到svg
元素。这里的定义是:
class Application {
int WIDTH = 80, HEIGHT = 60;
SvgSvgElement canvas;
Application(canvas_id) {
this.canvas = document.querySelector(canvas_id);
this.canvas.onDoubleClick.listen((MouseEvent e) => addUnit(e));
}
void addUnit(MouseEvent e) {
num x = e.offset.x - WIDTH/2;
num y = e.offset.y - HEIGHT/2;
BasicUnit newUnit = new BasicUnit(this.canvas, x, y, WIDTH, HEIGHT);
this.canvas.append(newUnit.group);
}
}
我的问题是,我的鼠标滑过BasicUnit
或<g>
元素。当您选择靠近其边缘的元素并尝试拖动时,突然元素会被删除。如果您尝试快速拖放,那也是如此。我试图按照this webpage上的示例进行操作,但无法弄清楚问题所在。
UPDATE 完整源代码可用here。
UPDATE II Here是一个演示。
我很欣赏你的努力,但滑动问题仍然存在。实际上,监听'canvas' onMouseMove'和'onMouseLeave'最终会被一个单元卡住,除非你将鼠标光标移出'canvas'。请参阅问题中的示例链接,该链接正常工作。 – mert
它工作正常,我没有遇到你遇到的问题。试试[这个例子](https://rawgithub.com/ringstaff/dart-drag-and-drop-svg/master/dart_drag_and_drop_svg_JS.html),让我知道你是否仍然看到相同的问题。 – ringstaff
我想我找到了你所指的问题。我会更新我的答案以反映我发现的内容。 – ringstaff