8
$\begingroup$

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?

$\endgroup$
2
  • $\begingroup$ Not clear what you want: already you can move any of the triangle's vertices by dragging its locator. Do you want to drag the entire triangle at once? $\endgroup$
    – murray
    Commented May 24, 2012 at 20:33
  • $\begingroup$ Yes. In the program I have, there are several shapes. I want to select one and drag all at once. Doing it per locator would change the area, that would be a problem in the prog. $\endgroup$ Commented May 24, 2012 at 21:13

1 Answer 1

7
$\begingroup$

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]]]]

Mathematica graphics

$\endgroup$
3
  • $\begingroup$ This is an example for "The Book". ;-) $\endgroup$ Commented May 25, 2012 at 6:55
  • $\begingroup$ When the polygons are positioned 'on top' of each other it is no longer possible to select and/or modify a locator. Is there a way around this? - I can make a new question if you like. $\endgroup$ Commented May 26, 2012 at 12:40
  • $\begingroup$ Played around with PassEventsDown and that did the trick, to my relief. $\endgroup$ Commented May 26, 2012 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.