Building a Pannable, Zoomable Canvas in React

A quick note, since I've gotten a few questions about this. The code for this post is not on GitHub. Feel free to use the code in this post under the MIT license:

Copyright (c) 2020 Jonathan Clem <>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Recently, I was tinkering on a side-project where I wanted to build a sort of canvas of very large dimensions that I could zoom in on and pan around, similar to zooming and panning around in a map application.

In this post, I'm going to detail how I built this in React and what challenges I had to overcome in doing so. The components I was building were only intended to be used in a desktop browser, so on touch-enabled devices, the examples have been replaced with illustrative video clips.

In my first attempts at building this pannable and zoomable canvas, I bound the canvas's pan and zoom state directly to the canvas's DOM element itself. Ultimately, this caused a lot problems, because there were certain elements visually laid out on the canvas that I either did not want to scale, or did not want to pan (such as some user interface elements on the canvas).

Ultimately, I decided to try an approach that decoupled the desired pan and zoom state entirely from the canvas component itself. Instead of binding the pan and zoom state to the canvas, I wanted to create a React context that reported the user's desired pan and zoom state, but didn't actually manipulate the DOM in any way.

Here's a simplified explanation of what I wanted in code:

1export type CanvasState {
2 // The pan state
3 offset: {x: number, y: number}
4 // The zoom state
5 scale: number
8export const CanvasContext = React.createContext<CanvasState>({} as any)

1function SomeCanvasComponent() {
2 const {state} = useContext(CanvasContext)
3 return <div>The desired user zoom level is {state.scale}.</div>

Here, you can see that CanvasContext doesn't do any direct manipulation of the DOM. It just tells SomeCanvasComponent that the user wants the scale to be at some value, and leaves it up to that component to actually reflect that desired state.

My first step was to implement the panning state. To do this, I implemented a usePan hook that that tracked the user panning around a component.

Essentially, usePan is a hook that returns a pan offset state and a function. The function should be called whenever the user starts a pan on the target element (usually a mousedown event). On each mousemove event until a mouseup occurs and we remove our event listeners, we calculate the delta between the last observed mouse position on mousemove and the current event's mouse position. Then, we apply that delta to our offset state.

One quick detail—you may wonder why the mousemove and mouseup event listeners in this hook are bound to document and not to the target element specified by the user. This is because we want to ensure that any mouse movement by the user whatsoever while panning, even if not over the target element itself, still pans the canvas. For example, on pages like this blog post where the canvas is contained within another bounding element, we don't want panning to stop just because the user's mouse happened to leave the bounding element.

Here is the usePan hook (note that you'll see the Point type and ORIGIN constant referenced in other places in this blog post):

1import {
2 MouseEvent as SyntheticMouseEvent,
3 useCallback,
4 useRef,
5 useState,
6} from 'react'
8type Point = {x: number; y: number}
9const ORIGIN = Object.freeze({x: 0, y: 0})
12 * Track the user's intended panning offset by listening to `mousemove` events
13 * once the user has started panning.
14 */
15export default function usePan(): [Point, (e: SyntheticMouseEvent) => void] {
16 const [panState, setPanState] = useState<Point>(ORIGIN)
18 // Track the last observed mouse position on pan.
19 const lastPointRef = useRef(ORIGIN)
21 const pan = useCallback((e: MouseEvent) => {
22 const lastPoint = lastPointRef.current
23 const point = {x: e.pageX, y: e.pageY}
24 lastPointRef.current = point
26 // Find the delta between the last mouse position on `mousemove` and the
27 // current mouse position.
28 //
29 // Then, apply that delta to the current pan offset and set that as the new
30 // state.
31 setPanState(panState => {
32 const delta = {
33 x: lastPoint.x - point.x,
34 y: lastPoint.y - point.y,
35 }
36 const offset = {
37 x: panState.x + delta.x,
38 y: panState.y + delta.y,
39 }
41 return offset
42 })
43 }, [])
45 // Tear down listeners.
46 const endPan = useCallback(() => {
47 document.removeEventListener('mousemove', pan)
48 document.removeEventListener('mouseup', endPan)
49 }, [pan])
51 // Set up listeners.
52 const startPan = useCallback(
53 (e: SyntheticMouseEvent) => {
54 document.addEventListener('mousemove', pan)
55 document.addEventListener('mouseup', endPan)
56 lastPointRef.current = {x: e.pageX, y: e.pageY}
57 },
58 [pan, endPan]
59 )
61 return [panState, startPan]

Let's use the usePan hook in a simple example that will just show us how much we've panned around total. Note that in this and other examples, I'm omitting styling for clarity:

1export const UsePanExample = () => {
2 const [offset, startPan] = usePan()
4 return (
5 <div onMouseDown={startPan}>
6 <span>{JSON.stringify(offset)}</span>
7 </div>
8 )

If you click on this example and drag around, you'll see a persistent measure of how far you've dragged both horizontally and vertically.

As you can see, this isn't really panning an element since neither it nor our viewport are moving, but later we'll see how these values can be used to simulate panning in various ways depending on our needs.

Now that I had the basics of panning state down, I needed to tackle scaling. For scaling, I decided to implement a hook called useScale. Much like usePan, it doesn't actually do any scaling or zooming. Instead, it listens on certain events and reports back what it thinks the user intends for the current scale level to be.

1import {RefObject, useState} from 'react'
2import useEventListener from './useEventListener'
4type ScaleOpts = {
5 direction: 'up' | 'down'
6 interval: number
9const MIN_SCALE = 0.5
10const MAX_SCALE = 3
13 * Listen for `wheel` events on the given element ref and update the reported
14 * scale state, accordingly.
15 */
16export default function useScale(ref: RefObject<HTMLElement | null>) {
17 const [scale, setScale] = useState(1)
19 const updateScale = ({direction, interval}: ScaleOpts) => {
20 setScale(currentScale => {
21 let scale: number
23 // Adjust up to or down to the maximum or minimum scale levels by `interval`.
24 if (direction === 'up' && currentScale + interval < MAX_SCALE) {
25 scale = currentScale + interval
26 } else if (direction === 'up') {
27 scale = MAX_SCALE
28 } else if (direction === 'down' && currentScale - interval > MIN_SCALE) {
29 scale = currentScale - interval
30 } else if (direction === 'down') {
31 scale = MIN_SCALE
32 } else {
33 scale = currentScale
34 }
36 return scale
37 })
38 }
40 // Set up an event listener such that on `wheel`, we call `updateScale`.
41 useEventListener(ref, 'wheel', e => {
42 e.preventDefault()
44 updateScale({
45 direction: e.deltaY > 0 ? 'up' : 'down',
46 interval: 0.1,
47 })
48 })
50 return scale
Note: You may be wondering why I'm manually attaching the `wheel` event instead of using a React `onWheel` listener. React has some surpising behavior and some bugs related to how it handles wheel events on components, so I am avoiding them by manually attaching an event listener. In this case I'm using a convenience hook called `useEventListener` that is just responsible for manually setting up and tearing down an event listener on a DOM node attached to the given ref:
import {RefObject, useEffect} from 'react'  

export default function useEventListener<
  K extends keyof GlobalEventHandlersEventMap
  ref: RefObject,
  event: K,
  listener: (event: GlobalEventHandlersEventMap[K]) => void,
  options?: boolean | AddEventListenerOptions
) {
  useEffect(() => {
    const node = ref.current

    if (!node) {

    const listenerWrapper = ((e: GlobalEventHandlersEventMap[K]) =>
      listener(e)) as EventListener

    node.addEventListener(event, listenerWrapper, options)

    return () => node.removeEventListener(event, listenerWrapper)
  }, [ref, event, listener, options])

Let's use the useScale hook in an example:

1export const UseScaleExample = () => {
2 const ref = useRef<HTMLDivElement | null>(null)
3 const scale = useScale(ref)
5 return (
6 <div ref={ref}>
7 <span>{scale}</span>
8 </div>
9 )

If you scroll up and down inside the example's bounding box, you should see the scale value update.

Now that we have our usePan and useScale hooks, how do we actually create a pannable, zoomable canvas? Or rather, how do we create the illusion of a pannable, zoomable canvas? For my particular use case, I knew that I could create the illusion of panning and scaling by manipulating the canvas's background offset for panning, and the canvas's scale for scaling, rather than actually trying to move the element itself around.

1export const UsePanScaleExample = () => {
2 const [offset, startPan] = usePan()
3 const ref = useRef<HTMLDivElement | null>(null)
4 const scale = useScale(ref)
6 return (
7 <div ref={ref} onMouseDown={startPan}>
8 <div
9 style={{
10 backgroundImage: 'url(/grid.svg)',
11 transform: `scale(${scale})`,
12 backgroundPosition: `${-offset.x}px ${-offset.y}px`,
13 }}
14 ></div>
15 </div>
16 )

We're on our way, but not quite there! In this example, panning seems to work fine! The background position updates according to the reported offset from usePan. Scaling kind of works, but unfortunately, as we scale the element down, we end up exposing a buffer between its edges and its bounding box. It doesn't really feel like we're zooming in and out on the canvas so much as it feels like we're zooming in and out on our tiny window into the canvas.

In order to solve this, I decided to use calculate a buffer based on the bounding box around the canvas itself. This buffer represents horizontal and vertical space we need to fill between the bounding box and what would normally be the edge of the zoomed out canvas. We can calculate this buffer for each side every time the scale changes using the formula $xbuf = (boundingWidth - boundingWidth / scale) / 2$. In plain English, the buffer to apply to each horizontal side is equal to one half of the width of the bounding element minus the width of the bounding element divided by the current scale. The same holds true for for the vertical sides, only one would use the bounding element's height.

1export const BufferExample = () => {
2 const [buffer, setBuffer] = useState(pointUtils.ORIGIN)
3 const [offset, startPan] = usePan()
4 const ref = useRef<HTMLDivElement | null>(null)
5 const scale = useScale(ref)
7 useLayoutEffect(() => {
8 const height = ref.current?.clientHeight ?? 0
9 const width = ref.current?.clientWidth ?? 0
11 // This is the application of the above formula!
12 setBuffer({
13 x: (width - width / scale) / 2,
14 y: (height - height / scale) / 2,
15 })
16 }, [scale, setBuffer])
18 return (
19 <div ref={ref} onMouseDown={startPan} style={{position: 'relative'}}>
20 <div
21 style={{
22 backgroundImage: 'url(/grid.svg)',
23 transform: `scale(${scale})`,
24 backgroundPosition: `${-offset.x}px ${-offset.y}px`,
25 position: 'absolute',
26 bottom: buffer.y,
27 left: buffer.x,
28 right: buffer.x,
29 top: buffer.y,
30 }}
31 ></div>
32 </div>
33 )

In this example, we absolutely position the actual canvas background DOM node within the bounding element and use the calculated buffer values to set the top, right, bottom, and left positions. Essentially, if the user has scaled out to 0.5 and the bounding element is 100 pixels wide, we know that we need to set the left and right positions out 50 pixels further than usual, so we set them each to -50px.

Now, we have a canvas that feels infinite in size (barring integer overflow) that we can pan and zoom on. I was proud of this accomplishment, but something still didn't feel quite right about it. You'll notice that when you zoom, the focal point is always the top-left corner of the bounding container—you're always going to be zooming in on that corner, and then would have to pan to your destination (or place it in the corner before zooming). I have seen other implementations solve this by always just zooming into the exact center of the canvas, where the user may be somewhat more likely to have placed the area they are trying to focus in on. To me, this still felt like it was putting a lot of burden on the user to position things in the exact right place before zooming.

Instead, I wanted to find the point to zoom in on dynamically, under the assumption that the mouse pointer is probably pointing at the thing the user is trying to focus on. In order to accomplish this, I made several important changes to the component.

First, I implemented a hook called useMousePos. I won't show its source code here, but essentially it just returns a ref whose value is the last known position of the user's mouse pointer, based on listening to mousemove and wheel events on the canvas's bounding container.

Then, I implemented a hook called useLast. This hook maintains a reference to the previous value passed to it and returns that last known value. This is just an easy way to track the last known value of scale and offset and the current value. We'll get to why this is necessary shortly.

Finally, calculating the adjusted offset based on the user's mouse position as the user scales is where things get really tricky. In order to store this adjusted value, I create a container ref for it called adjustedOffset. If on any given render the scale has not changed (lastScale === scale), we set the adjusted offset to be the sum of the current adjusted offset and the delta between the current and last non-adjusted offset, scaled according to our current scale value. In other words, when the scale has not changed:

$$ adjOffset = adjOffset + (offsetDelta / scale) $$

Keep in mind that the math operations here are on points, so $+$ is summing the $x$ and $y$ values of each point. We "scale" a point by dividing by the scale value (so if the user pans by 10 pixels but scale is 0.5, we adjust that delta value to 10 / 0.5, yielding 20 pixels at our current scale).

When we want to get the adjusted offset when the scale has changed, we need to do things a little differently, because we now want to ensure that the focal point of the change in scale is the user's mouse pointer. In other words, as we scale (as long as the user is not panning at the same time), the point on the canvas directly under the user's mouse pointer should not change. First, we get the mouse position adjusted according to the last known scale value:

$$ lastMouse = mousePos / lastScale $$

Then, we get the mouse position adjusted according to the current scale value:

$$ newMouse = mousePos / scale $$

Next, we calculate how much the mouse has moved relative to our canvas as a result of the scaling by subtracting the $newMouse$ value from the $lastMouse$ value. This will tell us how much we need to adjust our offset by in order to compensate for the change in relative position of the mouse pointer to the canvas as a result of the scaling:

$$ mouseOffset = lastMouse - newMouse $$

Finally, we set apply this offset by adding the $mouseOffset$ we calculated to the current adjusted offset value:

$$ adjOffset = adjOffset + mouseOffset $$

Rather than using our offset provided by usePan, we now use our new adjusted offset, which maintains our pan offset relative to the user's mouse position as they zoom in and out.

1export const TrackingExample = () => {
2 const [buffer, setBuffer] = useState(pointUtils.ORIGIN)
3 const ref = useRef<HTMLDivElement | null>(null)
4 const [offset, startPan] = usePan()
5 const scale = useScale(ref)
7 // Track the mouse position.
8 const mousePosRef = useMousePos(ref)
10 // Track the last known offset and scale.
11 const lastOffset = useLast(offset)
12 const lastScale = useLast(scale)
14 // Calculate the delta between the current and last offset—how far the user has panned.
15 const delta = pointUtils.diff(offset, lastOffset)
17 // Since scale also affects offset, we track our own "real" offset that's
18 // changed by both panning and zooming.
19 const adjustedOffset = useRef(pointUtils.sum(offset, delta))
21 if (lastScale === scale) {
22 // No change in scale—just apply the delta between the last and new offset
23 // to the adjusted offset.
24 adjustedOffset.current = pointUtils.sum(
25 adjustedOffset.current,
26 pointUtils.scale(delta, scale)
27 )
28 } else {
29 // The scale has changed—adjust the offset to compensate for the change in
30 // relative position of the pointer to the canvas.
31 const lastMouse = pointUtils.scale(mousePosRef.current, lastScale)
32 const newMouse = pointUtils.scale(mousePosRef.current, scale)
33 const mouseOffset = pointUtils.diff(lastMouse, newMouse)
34 adjustedOffset.current = pointUtils.sum(adjustedOffset.current, mouseOffset)
35 }
37 useLayoutEffect(() => {
38 const height = ref.current?.clientHeight ?? 0
39 const width = ref.current?.clientWidth ?? 0
41 setBuffer({
42 x: (width - width / scale) / 2,
43 y: (height - height / scale) / 2,
44 })
45 }, [scale, setBuffer])
47 return (
48 <div ref={ref} onMouseDown={startPan} style={{position: 'relative'}}>
49 <div
50 style={{
51 backgroundImage: 'url(/grid.svg)',
52 transform: `scale(${scale})`,
53 backgroundPosition: `${-adjustedOffset.current.x}px ${-adjustedOffset
54 .current.y}px`,
55 position: 'absolute',
56 bottom: buffer.y,
57 left: buffer.x,
58 right: buffer.x,
59 top: buffer.y,
60 }}
61 ></div>
62 </div>
63 )

In this example, notice that as you zoom in and out, the focal point always remains the mouse cursor, even if you pan and zoom simultaneously, or move the mouse as you zoom.

With this final addition, I had something that felt very natural to use, much like a maps application. I was surprised at the complexity required to build a good user experience for something that seems relatively simple—surely, there are simplifications that could be made here and probably a few bugs in the React code, as well.

Now, I was ready to wrap this component up into a context. Thankfully, that was pretty easy!

1export type CanvasState {
2 offset: Point
3 buffer: Point
4 scale: number
7export const CanvasContext = React.createContext<CanvasState>({} as any)
9export default function CanvasProvider(props: PropsWithChildren<unknown>) {
10 // Insert here all of the hooks from the previous example!
12 return (
13 <CanvasContext.Provider
14 value={{
15 offset: adjustedOffset.current,
16 scale,
17 buffer
18 }}
19 >
20 <div ref={ref} onMouseDown={startPan} style={{position: 'relative'}}>
21 {props.children}
22 </div>
23 </CanvasContext.Provider>
24 )

And to consume the context to get the grid effect in the prior example:

1export default function GridBackground() {
2 const {offset, buffer, scale} = useContext(CanvasContext)
4 return (
5 <div
6 style={{
7 backgroundImage: 'url(/grid.svg)',
8 transform: `scale(${scale})`,
9 backgroundPosition: `${-offset.x}px ${-offset.y}px`,
10 position: 'absolute',
11 bottom: buffer.y,
12 left: buffer.x,
13 right: buffer.x,
14 top: buffer.y,
15 }}
16 ></div>
17 )

Now that we have our basic canvas container and context set up, there's a lot more we can do just by consuming the desired state of the canvas view. In a future blog post, I hope to show how I've also implemented a feature where cards can be added to this canvas by command-clicking at the desired position.

Thanks for reading!