javascript - React 中使用鼠标滚轮缩放图像

标签 javascript reactjs

所以我正在尝试重拍this version (取自 this post 并进行修改)在 React 中使用鼠标滚轮进行图像缩放。

问题是,即使在 React 中使用相同的数学和逻辑,它也不能完美地工作,我不知道为什么。图像似乎没有在光标所在的位置缩放。

这是我的组件:

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>
  );
};

我做了一个CodeSandbox: https://codesandbox.io/s/lingering-breeze-ho4do?file=/src/App.js

当光标位于图像右下角时尝试缩放,您会发现问题。

最佳答案

抱歉,请仔细阅读您的问题。问题是transform order matters 。您需要交换比例和变换( https://codesandbox.io/s/wonderful-cerf-69doe?file=/src/App.js )。祝你的项目好运。

关于javascript - React 中使用鼠标滚轮缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64386897/

相关文章:

javascript - chrome 不渲染 gif 背景图片

javascript - 递归调用多个嵌套对象给出未定义

javascript - 无法从 watchpack-chokidar2 :fsevents 访问 NPM CI 错误绑定(bind)

javascript - 替换字符串,除非它在给定字符串的某个子字符串中

javascript - xhr 请求控制源

javascript - 更新状态时,map 不是函数

reactjs - 在 typescript 中将 useState 作为 props 传递

reactjs - Firebase 错误 : Missing or insufficient permissions with react js

reactjs - React-Router:如何检索当前路由的父路由?

javascript - Chrome 浏览器中的 JSX 转换