8

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?

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
nilo de roock
  • 9,657
  • 3
  • 35
  • 77
  • 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? – murray May 24 '12 at 20:33
  • 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. – nilo de roock May 24 '12 at 21:13

1 Answers1

7

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

Heike
  • 35,858
  • 3
  • 108
  • 157