2

So I'm trying to remake this version (taken and modified from this post) of an image zoom using the mouse wheel in React.

The thing is, even with the same maths and logic in React, it doesn't perfectly work and I have no idea why. It seems like the image doesn't zoom where the cursor is.

Here's my component:

import React, { useState } from "react";

export default () => {
  const [pos, setPos] = useState({ x: 0, y: 0, scale: 1 });

  const onScroll = (e) => {
    const delta = e.deltaY * -0.01;
    const newScale = pos.scale + delta;

    const ratio = 1 - newScale / pos.scale;

    setPos({
      scale: newScale,
      x: pos.x + (e.clientX - pos.x) * ratio,
      y: pos.y + (e.clientY - pos.y) * ratio,
    });
  };

  return (
    <div onWheelCapture={onScroll}>
      <img
        src="https://source.unsplash.com/random/300x300?sky"
        style={{
          transformOrigin: "0 0",
          transform: `scale(${pos.scale}) translate(${pos.x}px, ${pos.y}px)`,
        }}
      />
    </div>
  );
};

I made a CodeSandbox: https://codesandbox.io/s/lingering-breeze-ho4do?file=/src/App.js

Try to zoom while your cursor is around the bottom right of the image, you'll see the issue.

Anatole Lucet
  • 1,603
  • 3
  • 24
  • 43
  • I think you just copied the code a bit wrong, it's not the same, your delta property is different. Check out: https://codesandbox.io/s/beautiful-cannon-wxwxm?file=/src/App.js – atomictom Oct 16 '20 at 10:26
  • @atomictom Indeed, I said I've modified a bit what was on the post I linked. Here's my vanilla version: https://jsfiddle.net/wdahrxbs/5/ As you can see I'm using the same delta as in my React component, but the vanilla version works while the React one doesn't. And the CodeSandbox you sent has the same issue :( – Anatole Lucet Oct 16 '20 at 10:32

1 Answers1

3

Sorry, read your question a bit more closely. The issue is transform order matters. You need to swap around scale and transform (https://codesandbox.io/s/wonderful-cerf-69doe?file=/src/App.js). Good luck with your project .

atomictom
  • 1,637
  • 16
  • 14