我嘗試使用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