img-previewer
View images the way iOS Photos does: a photo grows from its spot to the center of the screen and shrinks back when closed. Every animation runs on CSS transforms, so it stays smooth.
- ≈ 5 KB JS gzipped
- 0 dependencies
- Pinch to zoom and keyboard shortcuts
npm i img-previewer
Controls
Once a photo is open you can use these. On touch screens, pinch to zoom.
- ZoomMouse wheel or + -
- PanDrag after zooming in
- Previous / next← →
- CloseEsc or click the backdrop
- Rotate, zoom and resetToolbar, top right
Install
npm i img-previewer
# or
pnpm add img-previewer
Or load it from a CDN:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/img-previewer/dist/index.css">
<script src="https://cdn.jsdelivr.net/npm/img-previewer/dist/img-previewer.min.js"></script>
Usage
Pass a CSS selector. Every <img> inside it opens on click, with no changes to your existing HTML.
import ImgPreviewer from 'img-previewer'
import 'img-previewer/dist/index.css'
const previewer = new ImgPreviewer('#app', {
fillRatio: 0.8,
onShow({ index, img }) {},
onHidden({ index, img }) {}
})
Adding images later? Call previewer.update() after they render.
Options
| Name | Description | Default |
|---|---|---|
fillRatio | How much of the viewport the image fills | 0.8 |
dataUrlKey | Attribute that holds the full-size image URL | src |
triggerEvent | Event that opens the viewer, click or dblclick | click |
imageZoom | Zoom: min, max, step | 1 / 5 / 0.1 |
style | Style: modalOpacity, headerOpacity, zIndex | 0.6 / 0 / 99 |
i18n | Toolbar tooltip text. Chinese or English by browser language | Auto |
bubblingLevel | How many parent levels to check for CSS hiding | 0 |
hideOriginal | Hide the original image on the page while previewing | true |
duration | Open and close animation duration in ms, switching and zooming scale with it | 400 |
onBeforeShow | Called before opening, return false to cancel | — |
onShow | Called when the viewer starts opening | — |
onShown | Called after the open animation | — |
onChange | Called when switching images, also gets prevIndex | — |
onBeforeHide | Called before closing, return false to cancel | — |
onHide | Called when the viewer starts closing (alias onClose) | — |
onHidden | Called after the close animation | — |
Lifecycle hooks receive { index, img }, where img is the original image on the page.
Methods
| Method | Description |
|---|---|
show(index) | Open the image at an index |
next() / prev() | Go to the next / previous image |
hide() | Close the viewer |
update() | Re-collect images under the selector |
getTotalIndex() | Index of the last image |
destroy() | Remove listeners and DOM created by the instance |