useZoom
Add scroll-based zoom functionality to any <img /> element.
Import
import { useZoom } from '@hoverinc/design-system-react-web';
Options
| Option | Type | Default | Description |
|---|---|---|---|
zoom | number | 0.1 | Zoom factor applied on each scroll event (controls the speed of the zoom) |
maxZoom | number | false | false | Maximum zoom level allowed (e.g: 5 maxes out the image at 5 times the original size) |
initialZoom | number | 1 | Initial zoom level (use in combination with initialX and initialY to zoom to specific region of the image) |
initialX | number | 0.5 | Initial horizontal offset (for use with initialZoom) |
initialY | number | 0.5 | Initial horizontal offset (for use with initialZoom) |
ZoomOptions props
Import the ZoomOptions type to incorporate zoom options into your component's
props.
import { Image, ImageProps } from '@hoverinc/design-system-react-web';import type { ZoomOptions } from '@hoverinc/design-system-react-web';interface ZoomImageProps extends ImageProps { zoomOptions?: ZoomOptions;}export const ZoomImage = ({ zoomOptions, ...props }: ZoomImageProps) => { const { props } = useZoom({ maxZoom: 10, ...zoomOptions }); return <Image cursor="zoom-in" {...props} />;};
Usage
Simply spread the returned props object into the target image element. Note
that the props object includes a ref that is required for zoom to work so be
careful not to overwrite it.
Resize
If it's possible that the image element's size will change, you'll need to call
resize. Depending on what triggers the resize, you can use the resize event on
window, a ResizeObserver like @chakra-ui/react-use-size's
useSize
hook, or another handler that you know will cause a resize.
Window resize
Here we're using vw units so we know a window resize will always resize the
image.
Breakpoint
Here we're using responsive style prop width and an effect depending on the
value of the useBreakpoint hook to
trigger a resize when the breakpoint changes.
Handler
Here we're resizing the image in an event handler so we can just invoke
resize() in the same handler.
Set Zoom
The useZoom hook returns the current zoomRatio and a setZoom method. This
enables consumers of the hook to build custom UI zoom controls.
Focus Box
The useZoom hook returns a focusBox method. The focusBox receives a
bounding box parameter and zooms and centers the bounding box as much as
possible while still respecting maxZoom.
The bounding box is defined using the natural dimensions of the image. The
natural dimensions are adjusted as needed by the useZoom hook to account for
differences between the natural dimensions and the dimensions of the image on
screen.
The maxZoom option can be passed to focusBox if a lower maxZoom is
desired. Passing a maxZoom higher than the maxZoom passed to useZoom is
ignored.