Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
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. –  ndroock1 May 24 '12 at 21:13
add comment

1 Answer

up vote 6 down vote accepted

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

share|improve this answer
    
This is an example for "The Book". ;-) –  ndroock1 May 25 '12 at 6:55
    
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. –  ndroock1 May 26 '12 at 12:40
    
Played around with PassEventsDown and that did the trick, to my relief. –  ndroock1 May 26 '12 at 13:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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