How to Zoom an Image with the Wheel and Drag It in React
If you keep the zoom factor and the position of an image in one state and apply translate() and scale() with the CSS transform, you can build an image frame that zooms with the wheel and moves by dragging, without a library. If you also recalculate the position when zooming, the point under the cursor stays where it is while the image zooms.
Be careful about how you receive wheel events. Inside a JSX onWheel, preventDefault() had no effect: when I turned the wheel to zoom out, the page scrolled as well. Registering the handler with addEventListener() and passive: false stops the scrolling.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, and Playwright 1.63.0. I operated the mouse wheel and dragging with Playwright, and sent touch input with the Input.dispatchTouchEvent command of the Chrome DevTools Protocol (CDP). I did not test Firefox, Safari, real smartphones, or trackpads. Pinch zoom with two fingers is also outside the scope of this article.

- 1. ZoomPanImage, which holds the zoom and position in state
- 2. Zooming while keeping the point under the cursor fixed
- 3. If the frame border is drawn with border, the point under the cursor shifts
- 4. onWheel cannot stop the page from scrolling
- 5. When registering with addEventListener, read state with an updater function
- 6. Dragging to move
- 7. Zoom buttons for environments without a wheel
ZoomPanImage, which holds the zoom and position in state
This is the component ZoomPanImage for one display frame. The state view holds the zoom factor (scale) and how far the top-left corner of the image is offset from the top-left corner of the frame (x and y).
import { useEffect, useRef, useState } from 'react';
import type { PointerEvent } from 'react';
type Props = {
src: string;
alt: string;
width: number; // Width of the frame (px). The image is displayed at this width.
height: number; // Height of the frame (px).
};
// Scale factor, and the image's top-left position (in px from the frame's top-left).
type View = { scale: number; x: number; y: number };
const MIN_SCALE = 1;
const MAX_SCALE = 8;
// When the wheel deltaY is 100, scale by about 1.22 times (e to the power of 0.2).
const ZOOM_SPEED = 0.002;
// Clamp the position so the image can't move outside the frame, leaving no empty space inside it.
function clampView(v: View, width: number, height: number): View {
const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, v.scale));
const minX = width - width * scale;
const minY = height - height * scale;
return {
scale,
x: Math.min(0, Math.max(minX, v.x)),
y: Math.min(0, Math.max(minY, v.y)),
};
}
// Set the scale to nextScale while keeping the image point under (px, py) in the frame fixed in place.
function zoomAt(v: View, nextScale: number, px: number, py: number, width: number, height: number): View {
const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, nextScale));
// The point under (px, py) in the frame, as a position on the image (in px at scale 1).
const ix = (px - v.x) / v.scale;
const iy = (py - v.y) / v.scale;
return clampView({ scale, x: px - ix * scale, y: py - iy * scale }, width, height);
}
type Drag = { pointerId: number; startX: number; startY: number; origin: View };
export function ZoomPanImage({ src, alt, width, height }: Props) {
const [view, setView] = useState<View>({ scale: 1, x: 0, y: 0 });
const frameRef = useRef<HTMLDivElement>(null);
const drag = useRef<Drag | null>(null);
// Register wheel with addEventListener and passive: false.
useEffect(() => {
const el = frameRef.current;
if (!el) return;
function handleWheel(e: WheelEvent) {
e.preventDefault(); // Stop the page from scrolling.
const rect = el!.getBoundingClientRect();
const px = e.clientX - rect.left;
const py = e.clientY - rect.top;
const factor = Math.exp(-e.deltaY * ZOOM_SPEED);
// Since it is registered only once, receive the current view through an update function.
setView((v) => zoomAt(v, v.scale * factor, px, py, width, height));
}
el.addEventListener('wheel', handleWheel, { passive: false });
return () => el.removeEventListener('wheel', handleWheel);
}, [width, height]);
function handlePointerDown(e: PointerEvent<HTMLDivElement>) {
if (e.pointerType === 'mouse' && e.button !== 0) return;
e.currentTarget.setPointerCapture(e.pointerId);
drag.current = { pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, origin: view };
}
function handlePointerMove(e: PointerEvent<HTMLDivElement>) {
const d = drag.current;
if (!d || d.pointerId !== e.pointerId) return;
const next = {
scale: d.origin.scale,
x: d.origin.x + (e.clientX - d.startX),
y: d.origin.y + (e.clientY - d.startY),
};
setView(clampView(next, width, height));
}
function handlePointerEnd(e: PointerEvent<HTMLDivElement>) {
if (drag.current?.pointerId === e.pointerId) drag.current = null;
}
// Buttons zoom in and out relative to the center of the frame.
function zoomBy(factor: number) {
setView((v) => zoomAt(v, v.scale * factor, width / 2, height / 2, width, height));
}
return (
<div className="zoom-pan">
<div
ref={frameRef}
className="zoom-frame"
style={{ width, height }}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerEnd}
onPointerCancel={handlePointerEnd}
>
<img
src={src}
alt={alt}
width={width}
height={height}
draggable={false}
style={{ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})` }}
/>
</div>
<div className="zoom-controls">
<button type="button" onClick={() => zoomBy(1 / 1.5)} disabled={view.scale <= MIN_SCALE}>
縮小
</button>
<output aria-live="polite">{Math.round(view.scale * 100)}%</output>
<button type="button" onClick={() => zoomBy(1.5)} disabled={view.scale >= MAX_SCALE}>
拡大
</button>
<button type="button" onClick={() => setView({ scale: 1, x: 0, y: 0 })}>
元に戻す
</button>
</div>
</div>
);
}
The image gets translate(x, y) scale(scale). The CSS sets transform-origin: 0 0, so the zoom is anchored at the top-left corner of the image. Without setting transform-origin, the anchor is the center of the element. In Chromium, getComputedStyle() returned 160px 120px (the center of the 320×240 element) when I did not set it, and 0px 0px when I set 0 0. With the anchor at the top-left, a point (ix, iy) on the image appears at (x + ix × scale, y + iy × scale) inside the frame, which keeps the math simple.
The zoom range is 1× to 8×. clampView() limits x to the range from "frame width minus the zoomed image width" up to 0, so the image cannot be moved far enough to leave a gap inside the frame. y is limited the same way using the height.
The CSS is as follows.
.zoom-frame {
overflow: hidden; /* Hide the zoomed image's parts that extend outside the frame. */
position: relative;
outline: 1px solid #9aa5ab; /* With a border, the top-left of getBoundingClientRect() and the image's top-left will be offset. */
cursor: grab;
touch-action: none; /* Stop the browser from using touch movement for scrolling or zooming. */
user-select: none;
}
.zoom-frame:active { cursor: grabbing; }
.zoom-frame img {
display: block;
transform-origin: 0 0; /* Make the zoom origin the image's top-left corner. */
}
overflow: hidden hides the parts of the zoomed image that fall outside the frame. touch-action: none tells the browser not to start scrolling or zooming when a finger moves across the element (see MDN's explanation of touch-action). draggable={false} on the image makes the image non-draggable. According to MDN's explanation of the draggable attribute, if you do not set it, an image can be dragged with the browser's default behavior.
The frame border is drawn with outline instead of border. The reason is explained in the section "If the frame border is drawn with border, the point under the cursor shifts."
The parent App only passes the image file and the frame size.
import { ZoomPanImage } from './ZoomPanImage';
export function App() {
return (
<main>
<ZoomPanImage src="map.png" alt="町の地図(マス目に A1〜H6 の番号付き)" width={320} height={240} />
</main>
);
}
Zooming while keeping the point under the cursor fixed
zoomAt() is the function that does the zoom math. First, it finds where the point under the cursor (px, py) is on the image.
ix = (px - x) / scale
iy = (py - y) / scale
After changing the zoom factor, it back-calculates the new x and y so that the same point stays at (px, py).
x' = px - ix * scale'
y' = py - iy * scale'
I drew a pink circle at (80, 80) on the image displayed at 320×240, placed the cursor on it, and turned the wheel. In this article, "up" means the direction where deltaY is negative (scrolling the page up), and "down" means the direction where it is positive. I used Playwright's mouse.wheel() and sent 100 for deltaY each time.
上へ(deltaY -100)1回目: 表示 122% / translate(-17.7px, -17.7px) scale(1.2214) / scrollY 0 / カーソルの下: (80, 80)
上へ(deltaY -100)2回目: 表示 149% / translate(-39.3px, -39.3px) scale(1.4918) / scrollY 0 / カーソルの下: (80, 80)
上へ(deltaY -100)3回目: 表示 182% / translate(-65.8px, -65.8px) scale(1.8221) / scrollY 0 / カーソルの下: (80, 80)
下へ(deltaY +100)1回目: 表示 149% / translate(-39.3px, -39.3px) scale(1.4918) / scrollY 0 / カーソルの下: (80, 80)
下へ(deltaY +100)2回目: 表示 122% / translate(-17.7px, -17.7px) scale(1.2214) / scrollY 0 / カーソルの下: (80, 80)
下へ(deltaY +100)3回目: 表示 100% / translate(0px, 0px) scale(1) / scrollY 0 / カーソルの下: (80, 80)
下へ(deltaY +100)4回目: 表示 100% / translate(0px, 0px) scale(1) / scrollY 0 / カーソルの下: (80, 80)
上へ12回: 表示 800% / translate(-560px, -560px) scale(8) / scrollY 0 / カーソルの下: (80, 80)
When deltaY is negative, Math.exp(-deltaY * 0.002) is greater than 1, so the image zooms in. Each step is about 1.22×. Because the zoom changes by multiplication rather than addition, turning the wheel down the same number of times returned exactly to 100%. The zoom stopped at 8× and did not go below 1×. At every step, the point under the cursor stayed at the pink circle's (80, 80).
For comparison, I also ran a version that changed only the zoom factor and kept the position as it was.
比べる用(拡大率だけを変え、位置はそのまま):
1回目: 表示 122% / translate(0px, 0px) scale(1.2214) / scrollY 0 / カーソルの下: (65.5, 65.5)
2回目: 表示 149% / translate(0px, 0px) scale(1.4918) / scrollY 0 / カーソルの下: (53.6, 53.6)
3回目: 表示 182% / translate(0px, 0px) scale(1.8221) / scrollY 0 / カーソルの下: (43.9, 43.9)
In this version, the image grows only from its top-left corner, so the pink circle moves away from the cursor toward the bottom right. After the third turn, the point under the cursor was at (43.9, 43.9). Even if you place the cursor on the spot you want to look at, that spot moves away from the cursor.
The deltaY value you receive from the wheel is not always in pixels. The MDN explanation of deltaY says that the unit depends on deltaMode, so you should check it. The code in this article treats the value as pixels, and I tested it only in Chromium. Also, according to the Pointer Events specification's description of wheel events, a positive deltaY points toward the bottom edge of the page. However, which physical direction of the wheel or trackpad gives a positive value can vary with the environment and device settings.
If the frame border is drawn with border, the point under the cursor shifts
handleWheel takes the cursor position (px, py) as the distance from the top-left corner of the frame's getBoundingClientRect(), and passes it to zoomAt(). The rectangle returned by getBoundingClientRect() includes the border. So if you draw the frame line with border, the top-left corner of the rectangle and the top-left corner of the image are offset by the border width, and the point zoomAt() treats as "under the cursor" shifts too. This is why the CSS in this article draws the line with outline.
I used a version with a 1px border and turned the wheel up three times over the pink circle, as in the previous section.
枠の getBoundingClientRect() の左上: (20, 16) / 画像の左上: (21, 17)
1回目: 表示 122% / translate(-17.9px, -17.9px) scale(1.2214) / scrollY 0 / カーソルの下: (80.2, 80.2)
2回目: 表示 149% / translate(-39.8px, -39.8px) scale(1.4918) / scrollY 0 / カーソルの下: (80.3, 80.3)
3回目: 表示 182% / translate(-66.6px, -66.6px) scale(1.8221) / scrollY 0 / カーソルの下: (80.5, 80.5)
The top-left corner of the frame's getBoundingClientRect() was (20, 16), 1px away from the image's top-left corner (21, 17). Each zoom moved the point under the cursor slightly away from the pink circle's (80, 80), and by the third turn it was at (80.5, 80.5). In the code of this article, where the line is drawn with outline, the point stayed at (80, 80) every time.
onWheel cannot stop the page from scrolling
When you turn the wheel, the browser normally scrolls the page. Because I did not want scrolling while the pointer was over the image, I called preventDefault(). However, calling it inside a JSX onWheel did not stop the scrolling. I placed the cursor on the pink circle, turned the wheel up twice, and then down once. (I added space below the page so that it could scroll.)
記事のコード(addEventListener と passive: false):
-100 → 表示 122% / translate(-17.7px, -17.7px) scale(1.2214) / scrollY 0
-100 → 表示 149% / translate(-39.3px, -39.3px) scale(1.4918) / scrollY 0
+100 → 表示 122% / translate(-17.7px, -17.7px) scale(1.2214) / scrollY 0
比べる用(JSX の onWheel):
-100 → 表示 122% / translate(-17.7px, -17.7px) scale(1.2214) / scrollY 0
-100 → 表示 149% / translate(-39.3px, -39.3px) scale(1.4918) / scrollY 0
+100 → 表示 122% / translate(-17.7px, 0px) scale(1.2214) / scrollY 100
The onWheel version still zoomed the image, but when I turned the wheel down, the page also scrolled 100px. (When I turned it up, the page did not scroll because it was already at the top.) The vertical offset also came out as 0px, not the -17.7px of the article's code. I did not investigate the cause of this difference. The console showed the following error every time I turned the wheel.
onwheel.html: [error] Unable to preventDefault inside passive event listener invocation.
React registers event listeners not on each element but once on the root (the element passed to createRoot()). In React's ReactDOMRoot.js, listenToAllSupportedEvents() is called on the root element. Reading React's DOM source DOMPluginEventSystem.js, touchstart, touchmove, and wheel are registered with passive set. The comment says this matches what browsers already do by making these three passive on document. According to MDN's explanation of addEventListener(), a passive listener cannot cancel the event, so the browser starts scrolling without waiting for the listener to finish. Calling preventDefault() inside such a listener does nothing.
So in the code of this article, I register the handler directly on the frame element inside useEffect with addEventListener('wheel', handleWheel, { passive: false }). As MDN notes, when you want a listener to be non-passive, you pass false explicitly. The cleanup function calls removeEventListener() to unregister it.
Because preventDefault() is called only when the wheel is turned over the frame, the page scrolls normally outside the frame.
枠の下でホイール(deltaY +100): 表示 100% / translate(0px, 0px) scale(1) / scrollY 100
The code in this article calls preventDefault() even when scrolling down at 100% zoom. (In the "zooming while keeping the point under the cursor fixed" section, scrollY also stayed at 0 for "down (deltaY +100) 4th time".) As a result, while the cursor is over the image, the page cannot be scrolled with the wheel. If you place a large image on a long page, decide whether this behavior is acceptable.
When registering with addEventListener, read state with an updater function
The useEffect that registers the wheel listener has the dependency array [width, height]. As long as the frame size does not change, the handleWheel registered first keeps being used. So if this function reads view directly, it sees the value from the first render (zoom 1).
In the article's code, I pass an updater function to setView and receive the current value as the argument v. This is the same pattern as the official reference example that updates state from a previous state inside an Effect. For comparison, I ran a version that reads view directly, as in setView(zoomAt(view, view.scale * factor, ...)), and turned the wheel up three times.
比べる用(更新用の関数を使わず、view をそのまま読む):
1回目: 表示 122% / translate(-17.7px, -17.7px) scale(1.2214) / scrollY 0 / カーソルの下: (80, 80)
2回目: 表示 122% / translate(-17.7px, -17.7px) scale(1.2214) / scrollY 0 / カーソルの下: (80, 80)
3回目: 表示 122% / translate(-17.7px, -17.7px) scale(1.2214) / scrollY 0 / カーソルの下: (80, 80)
No matter how many times I turned the wheel, it stayed at 122%. Each time, the calculation was based on the view with zoom 1. The article's code reached 182% after three turns.
Dragging to move
When you press, dragging calls setPointerCapture() and stores the press position and the view at that moment in the ref drag. Each time the pointer moves, the offset from the press position is added to the stored x and y. If you call setPointerCapture(), the frame keeps receiving events until you release, even when the pointer leaves the frame.
After zooming to 182%, I dragged with the mouse.
ドラッグの前: 表示 182% / translate(-65.8px, -65.8px) scale(1.8221) / scrollY 0
右へ30px・下へ20px動かしている間: 表示 182% / translate(-35.8px, -45.8px) scale(1.8221) / scrollY 0
離したあと: 表示 182% / translate(-35.8px, -45.8px) scale(1.8221) / scrollY 0
左へ150px・下へ300px(枠の外まで)動かしている間: 表示 182% / translate(-185.8px, 0px) scale(1.8221) / scrollY 0
離したあと: 表示 182% / translate(-185.8px, 0px) scale(1.8221) / scrollY 0
右へ400px・上へ400px動かして離したあと: 表示 182% / translate(0px, -197.3px) scale(1.8221) / scrollY 0
Moving 30px right and 20px down changed x and y by exactly those amounts. When I moved 300px down, the image kept following even outside the frame, and y stopped at 0. Once the top edge of the image reached the top edge of the frame, it could not move down any further. When I moved far up and to the right, x stopped at 0 and y stopped at -197.3px, which is "240 − 240 × 1.8221".
I also tested touch. After zooming to 225% with the zoom buttons, I moved a finger 40px right and 30px down using CDP. No pointercancel was received, and the image moved by that amount.
拡大ボタンを2回: 表示 225% / translate(-200px, -150px) scale(2.25) / scrollY 0
指で右へ40px・下へ30px動かす: 表示 225% / translate(-160px, -120px) scale(2.25) / scrollY 0 / イベント: pointerdown pointerup
Zoom buttons for environments without a wheel
On touch-only devices, or when operating only with the keyboard, you cannot zoom with the wheel. So I placed a zoom-out button, a zoom-in button, and a reset button below the frame. The buttons zoom in and out by 1.5× each time, around the center of the frame. The magnification is shown in an output element with aria-live="polite" (I did not test screen reader announcements). The button labels in the code are in Japanese.
元に戻す: 表示 100% / translate(0px, 0px) scale(1) / scrollY 0 / 縮小ボタン disabled: true
拡大を1回: 表示 150% / translate(-80px, -60px) scale(1.5) / scrollY 0 / 枠の中心の下: (160, 120)
拡大をさらに5回: 表示 800% / translate(-1120px, -840px) scale(8) / scrollY 0 / 拡大ボタン disabled: true
Even after zooming, the point under the frame's center stayed at the image center (160, 120). At 100% the zoom-out button becomes disabled, and at 800% the zoom-in button does.
I also tested the keyboard. Focusing the zoom-in button and pressing Enter brought it to 150%. Moving to the reset button with Tab and pressing Space returned it to 100%.
「拡大」にフォーカスして Enter: 表示 150% / translate(-80px, -60px) scale(1.5) / scrollY 0
Tab のあとのフォーカス: 元に戻す
Space: 表示 100% / translate(0px, 0px) scale(1) / scrollY 0





