Consider the following snippet
pts = RandomReal[1, {3, 2}]
g = Graphics[{Polygon[Dynamic[pts]]}, PlotRegion -> {{0, 0}, {2, 2}}];
Panel[LocatorPane[Dynamic[pts], g]]
I would like to be able to drag the triangle as a whole. I found none and assume this has to be added via code, i.e. EventHandler but found no examples of this.
Question: How can I select, and act upon multiple locators, i.e. drag, scale, apply a transformation to the points?
Answer
Here's one way to do it. In this example I've used one list of points for the vertices of the two shapes. The inner EventHandler sets the flag drag which indicates which shape should be moved. The outer EventHandler actually moves the shape. Releasing the mouse resets drag to 0 again. I'm using PassEventsDown -> True in the outer event handlers to make sure that the mouse events are handed over from outer to the inner event handlers.
DynamicModule[{pts, range, gr, drag, pts0},
pts = RandomReal[1, {7, 2}];
range = {Span[1, 4], Span[5, 7]};
gr = {{Red, Polygon[Dynamic[pts[[range[[1]]]]]]},
{Blue, Polygon[Dynamic[pts[[range[[2]]]]]]}};
drag = 0;
Panel[LocatorPane[Dynamic[pts],
EventHandler[
Graphics[
EventHandler[gr[[#]],
{"MouseDown" :> (drag = #;
pts0 = # - MousePosition["Graphics"] & /@ pts[[range[[#]]]])}
] & /@ {1, 2},
PlotRange -> {{0, 2}, {0, 2}}],
{"MouseDragged" :>
If[drag > 0, pts[[range[[drag]]]] = # + MousePosition["Graphics"] & /@ pts0],
"MouseUp" :> (drag = 0)},
PassEventsDown -> True]]]]

Comments
Post a Comment