【发布时间】:2013-12-08 09:14:38
【问题描述】:
我尝试使用 SVG 在 Dart 中创建拖放行为。我有BasicUnits,基本上是GElement (<g>)s。现在它有一个body,即RectElement。我正在使用该元素来移动设备。这是定义:
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 上的示例进行操作,但无法弄清楚问题所在。
更新 完整的源代码可用here。
更新二 Here 是一个演示。
【问题讨论】: