EaselJS: connect 2 containers/shapes using a line

我是研究僧i 提交于 2019-12-22 00:17:43

问题


I want to be able to click on a container/shape and as I move the mouse a line that can be connected to another container/shape (with an arrow at one end) is drawn. Ideally I want this line to snap to the destination element.

I'm new to EaselJS and I've got no clue on how to go about this. This is the closes I've come across of here, and I can't make sense out of it: Drawing a Line in a html5 canvas using EaselJS


回答1:


Here is a quick demo I put together

The key steps are:

  • Listen for mousedown on the initial item
  • Create a shape to draw the connection when the mouse is pressed
  • Listen for mousemove and mouseup on the stage (Note: You can use pressmove on the target to make this work a little more cleanly, but you will not get additional rollovers)
  • On mousemove, redraw the connection. In this case, I placed the connection on top of the initial target, so I have to offset the end point to compensate. I did this to avoid tracking the initial target)
  • On mouse up, stop the mousemove/mouseup, and determine what the mouse was released on. In this case, I removed the connection if there was no target, and redrew the connection a different color (and snapped to the center) otherwise.

http://jsfiddle.net/lannymcnie/6rh7P/

// Listen for press
end.on("mousedown", handlePress);

// Listen for move/end
stage.addEventListener("stagemousemove", drawLine);
stage.addEventListener("stagemouseup", endDraw);

// Redraw (and remember to clear)
connection.graphics.clear()
   .s("#f00")
   .mt(0,0).lt(stage.mouseX-connection.x, stage.mouseY-connection.y);

// Get the drop target(s)
var targets = stage.getObjectsUnderPoint(stage.mouseX, stage.mouseY);

// Stop Listening
stage.removeEventListener("stagemousemove", drawLine);
stage.removeEventListener("stagemouseup", endDraw);
// Note: This will be a little harder if you are using object-oriented approach, because the scope gets lost.

I thought this was in interesting challenge to bang out in 15 minutes. Hope it helps! Cheers.

[UPDATE]

In EaselJS 0.8+, you can save any graphics command, and update its values any time. This prevents you from having to redraw your whole shape every frame. Quick example:

connection.graphics.s("#f00").mt(0,0);
var command = connection.graphics.lt(0,0).command;

// Then later
command.x = stage.mouseX-connection.x;
command.y = stage.mouseY-connection.y;
stage.update();

Here is a sample showing Graphics commands (unrelated to this example) http://jsfiddle.net/lannymcnie/L2tm9xdm/



来源:https://stackoverflow.com/questions/22828791/easeljs-connect-2-containers-shapes-using-a-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!