MinJieLiu 5 years ago
parent
commit
20f4f809ed
4 changed files with 41 additions and 20 deletions
  1. 1 1
      package.json
  2. 23 17
      src/PhotoView.tsx
  3. 15 0
      src/utils/correctSuitablePosition.ts
  4. 2 2
      src/utils/getSuitableImageSize.ts

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "react-photo-view",
-  "version": "0.4.2",
+  "version": "0.4.3",
   "description": "一款精致的 React 的图片预览组件",
   "author": "MinJieLiu",
   "license": "MIT",

+ 23 - 17
src/PhotoView.tsx

@@ -21,6 +21,7 @@ import {
 } from './types';
 import './PhotoView.less';
 import getSuitableImageSize from './utils/getSuitableImageSize';
+import correctSuitablePosition from './utils/correctSuitablePosition';
 
 export interface IPhotoViewProps {
   // 图片地址
@@ -274,18 +275,20 @@ export default class PhotoView extends React.Component<IPhotoViewProps, typeof i
     if (reachState !== ReachTypeEnum.Normal) {
       return;
     }
+    const position = getPositionOnMoveOrScale({
+      x,
+      y,
+      clientX,
+      clientY,
+      fromScale: scale,
+      // 若图片足够大,则放大适应的倍数
+      toScale: scale !== 1 ? 1 : Math.max(2, naturalWidth / width),
+    });
     this.setState({
       clientX,
       clientY,
-      ...getPositionOnMoveOrScale({
-        x,
-        y,
-        clientX,
-        clientY,
-        fromScale: scale,
-        // 若图片足够大,则放大适应的倍数
-        toScale: scale !== 1 ? 1 : Math.max(2, naturalWidth / width),
-      }),
+      ...position,
+      ...correctSuitablePosition(position),
     });
   };
 
@@ -299,17 +302,20 @@ export default class PhotoView extends React.Component<IPhotoViewProps, typeof i
       const endScale = scale - deltaY / 100 / 2;
       // 限制最大倍数和最小倍数
       const toScale = Math.max(Math.min(endScale, Math.max(maxScale, naturalWidth / width)), minScale);
+
+      const position = getPositionOnMoveOrScale({
+        x,
+        y,
+        clientX,
+        clientY,
+        fromScale: scale,
+        toScale,
+      });
       return {
         clientX,
         clientY,
-        ...getPositionOnMoveOrScale({
-          x,
-          y,
-          clientX,
-          clientY,
-          fromScale: scale,
-          toScale,
-        }),
+        ...position,
+        ...correctSuitablePosition(position),
       };
     });
   };

+ 15 - 0
src/utils/correctSuitablePosition.ts

@@ -0,0 +1,15 @@
+/**
+ * 纠正缩放后偏离中心区域位置
+ */
+export default function correctSuitablePosition({ x, y, scale }: { x: number; y: number; scale: number }) {
+  if (scale <= 1) {
+    return {
+      x: 0,
+      y: 0,
+    };
+  }
+  return {
+    x,
+    y,
+  };
+}

+ 2 - 2
src/utils/getSuitableImageSize.ts

@@ -8,8 +8,8 @@ export default function getSuitableImageSize(
   width: number;
   height: number;
 } {
-  let width = 0;
-  let height = 0;
+  let width;
+  let height;
   const { innerWidth, innerHeight } = window;
   if (naturalWidth < innerWidth && naturalHeight < innerHeight) {
     width = naturalWidth;