9

I am trying to do:

EventHandler[Graphics[{ (*stuff*) }],{{"MouseDragged","p"}:>(*pan the graphics*),  
{"KeyDown","z"}:>(*zoom in/out as the mouse moves up/down in the graphics*) }]

This would be similar to what we can do with Graphics3D, except when I "pan" the Graphics I want to change the PlotRange rather than move the Graphics around the window. BTW I will be using "MouseDown" for custom modification of the Graphics, and that's one of the reasons why I want pan/zoom associated with pressing keys.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Ted Ersek
  • 7,124
  • 19
  • 41
  • I think either Istvan (?) or Szabolcs (?) have posted what you want here or on Mathgroup. Whoever the author was I know I have seen this code before. – Mike Honeychurch Jun 19 '12 at 00:02
  • 3
    I think it is Szabolcs's MathGroup post – kglr Jun 19 '12 at 00:14
  • 1
    @Mike that's not quite the same thing because it zooms to a selected box. I believe Ted's request is for something like the zoom seen in graphics programs, PDF viewers, etc., where you have a zoom control, and separately a smooth pan when zoomed. – Mr.Wizard Jun 19 '12 at 01:09

1 Answers1

15

You could do something like this

DynamicModule[{range, ref, range0, fac = 2/3},
 range = range0 = 2 {{-1, 1}, {-1, 1}};
 EventHandler[
  Dynamic@Graphics[{Disk[]}, Axes -> True, PlotRange -> range],
  {"MouseDown" :> (ref = MousePosition["GraphicsImageScaled"]; range0 = range),
   "MouseDragged" :> (range = range0 + 
       (ref - MousePosition["GraphicsImageScaled"]) (range0[[All, 2]] - range0[[All, 1]])),
   "MouseClicked" :> Which[
     CurrentValue["AltKey"], 
     range = (range - MousePosition["Graphics"])*fac + MousePosition["Graphics"],
     CurrentValue["ShiftKey"], 
     range = (range - MousePosition["Graphics"])/fac +  MousePosition["Graphics"]]}]]

You can pan by dragging, zoom in by clicking somewhere in the plot while keeping the Alt-key depressed (or Cmd if you're on OS X), and zoom out by clicking while keeping the Shift-key depressed. The amount of zoom with each click is determined by fac.

Heike
  • 35,858
  • 3
  • 108
  • 157
  • 1
    If I attempt to copy and paste the accepted answer above into my 12.3, run it, then attempt to press the left mouse button and drag the mouse, it reproducibly crashes my system; tried it several times and it crashed each time. Mathematica simply vanishes from my screen and reports an error into the Event Viewer log. I have reported it to technical support. (*** edit ***) Also, the terminations seemed to have caused a persistent slow-down with the Mathematica notebook that crashed after I resume running Mathematica it even when I reboot; something appears to have permanently been changed in the – josh Sep 06 '21 at 15:52