@beoe/pan-zoom
Small JS library to add pan and zoom functionality to SVG (inline or image). It supports gestures for all types of devices:
intention | mouse | trackpad/touchpad | touchscren |
---|---|---|---|
pan | click + move | click + move | two finger drag |
zoom | Ctrl + wheel | pinch | pinch |
reset | double click | double click | double tap |
scroll | wheel | two finger drag | one finger drag |
Pay attention:
- gestures intentionally selected to not interfere with the system’s default scroll gestures, to avoid “scroll traps”
- all actions are available through gestures, so it works without UI. You can add UI, though. Library exposes methods for this, like
pan(dx, dy)
andzoom(scale)
- Cmd + click - zoom in
- Alt + click - zoom out
- First double click (tap) - zoom in x2
Usage
There are two flavors:
- Headless - without UI
- Default UI
Headless
If you have container element in HTML:
If you don’t have container element in HTML:
Additionally following CSS is required:
Instance methods:
on()
- adds event listenersoff()
- removes event listenerspan(dx, dy)
- pans imagezoom(scale)
- zooms imagereset()
- resets pan and zoom values
Default UI
Additionally, CSS to style UI required (for example with Tailwind):
You can configure HTML classes used by UI:
and message with instructions for the touchscreen:
Pixelation in Safari
Be aware that some CSS will cause pixelation of SVG on zoom (bug in Safari), for example:
will-change: transform;
transform: matrix3d(...);
transition-property: transform;
(it setles after animation, though)
TODO
- Do not stretch images if they are smaller than viewport
- Do not show PanZoom UI for small images
- Prevent clicks on drag or pan
- minimap and full-screen mode, like in reactflow
- Create a Rehype plugin to wrap images in a container (
<figure class="beoe"></figure>
) to avoid creating it on the client side.