簡體   English   中英

React-konva 移動縮放和可拖動圖像

[英]React-konva mobile zoom and draggable image

我正在使用 Konva.js 構建 canvas 應用程序。 此應用程序允許用戶拖動圖像並在任意點縮放。 這在桌面上完美運行。 但是,我喜歡這個應用程序能夠響應移動設備。 這里的問題是 canvas 縮放和圖像拖動不能同步工作。 由於“onTouchMove”事件在圖像拖動時起作用,因此該應用程序無法按預期工作。

import React, { useEffect, useState, useRef } from 'react';
import {
  Stage, Layer, Image,
} from 'react-konva';
import Rectangle from './rectangle.component';

const GenericCanvas = ({
  canvasWidth,
  canvasHeight,
  imageUrl,
  imgWidth,
  imgHeight,
  rects,
  zoom,
  imageMove,
  alpha,
  borderDash,
  rectDraggable,
  fillStatus,
  onClickRect,
  reset,
  setReset,
  imageType,
  displayedFigure,
  displayedTable,
  clickedRect
}) => {
  const [image, setImage] = useState(null);
  const [stageScale, setStageScale] = useState(1);
  const [stageX, setStageX] = useState(0);
  const [stageY, setStageY] = useState(0);
  const [lastX, setLastX] = useState(0);
  const [lastY, setLastY] = useState(0);
  const [hasImageLoaded, setHasImageLoaded] = useState(false);

  const handleImageLastPosition = (e) => {
    setLastX(e.target.attrs.x);
    setLastY(e.target.attrs.y);
  };

  const handleWheel = (e) => {
    e.evt.preventDefault();

    const scaleBy = 1.2;
    const stage = e.target.getStage();
    const oldScale = stage.scaleX();
    const mousePointTo = {
      x: stage.getPointerPosition().x / oldScale - stage.x() / oldScale,
      y: stage.getPointerPosition().y / oldScale - stage.y() / oldScale,
    };

    const newScale = e.evt.deltaY > 0
      ? (oldScale > 3 ? oldScale : (oldScale * scaleBy)) : oldScale < 1
        ? oldScale : (oldScale / scaleBy);

    setStageScale(newScale);
    setStageX(-(mousePointTo.x - stage.getPointerPosition().x / newScale) * newScale);
    setStageY(-(mousePointTo.y - stage.getPointerPosition().y / newScale) * newScale);
  };

  function getDistance(p1, p2) {
    return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  }

  function getCenter(p1, p2) {
    return {
      x: (p1.x + p2.x) / 2,
      y: (p1.y + p2.y) / 2,
    };
  }

  var lastCenter = null;
  var lastDist = 0;

  const handleMultiTouch = (e) => {
    e.evt.preventDefault();
    var touch1 = e.evt.touches[0];
    var touch2 = e.evt.touches[1];
    const stage = e.target.getStage();

    if (touch1 && touch2) {
      if (stage.isDragging()) {
        stage.stopDrag();
      }

      imageMove= false;

      var p1 = {
        x: touch1.clientX,
        y: touch1.clientY,
      };
      var p2 = {
        x: touch2.clientX,
        y: touch2.clientY,
      };

      if (!lastCenter) {
        lastCenter = getCenter(p1, p2);
        return;
      }
      var newCenter = getCenter(p1, p2);

      var dist = getDistance(p1, p2);

      if (!lastDist) {
        lastDist = dist;
      }

      // local coordinates of center point
      var pointTo = {
        x: (newCenter.x - stage.x()) / stage.scaleX(),
        y: (newCenter.y - stage.y()) / stage.scaleX(),
      };

      var scale = stage.scaleX() * (dist / lastDist);

      stage.scaleX(scale);
      stage.scaleY(scale);

      // calculate new position of the stage
      var dx = newCenter.x - lastCenter.x;
      var dy = newCenter.y - lastCenter.y;

      var newPos = {
        x: newCenter.x - pointTo.x * scale + dx,
        y: newCenter.y - pointTo.y * scale + dy,
      };

      stage.position(newPos);
      stage.batchDraw();

      lastDist = dist;
      lastCenter = newCenter;
    }
  };

  const multiTouchEnd = () => {
    lastCenter = null;
    lastDist = 0;
  }

  useEffect(() => {
    setHasImageLoaded(false);
    if (imageUrl) {
      const matchedImg = new window.Image();
      matchedImg.src = `${API_URL + imageUrl}`;
      matchedImg.onload = () => {
        setHasImageLoaded(true);
        setImage(matchedImg);
      };
    }

  }, [size, imageUrl]);

  let imgDraggable = true
  return (
    <Stage
      width={canvasWidth}
      height={canvasHeight}
      onWheel={zoom ? handleWheel : null}
      scaleX={stageScale}
      onTouchMove={handleMultiTouch}
      onTouchEnd={() => {
        multiTouchEnd()
      }}
      scaleY={stageScale}
      x={stageX}
      y={stageY}
    >
      <Layer>
        <Image
          x={lastX}
          y={lastY}
          ref={stageRef}
          image={image}
          width={imgWidth * alpha || 0}
          height={imgHeight * alpha || 0}
          onDragMove={(e) => {
            if (e.evt.touches.length === 2) {
              imgDraggable = false
            }
            handleImageLastPosition(e)
          }}
          draggable={imgDraggable}
        />
        {rects?.length && hasImageLoaded ?
          rects.map((rect) => 
            (
            <Rectangle
              key={uuid()}
              x={imageType === 'figure' ? rect.bbox.x0 * alpha + lastX : rect.PN_bbox.x0 * alpha + lastX}
              y={imageType === 'figure' ? rect.bbox.y0 * alpha + lastY : rect.PN_bbox.y0 * alpha + lastY}
              width={imageType === 'figure' ? rect.bbox.x1 * alpha - rect.bbox.x0 * alpha : rect.PN_bbox.x1 * alpha - rect.PN_bbox.x0 * alpha}
              height={imageType === 'figure' ? rect.bbox.y1 * alpha - rect.bbox.y0 * alpha : rect.PN_bbox.y1 * alpha - rect.PN_bbox.y0 * alpha}
              rectDraggable={rectDraggable}
              borderDash={borderDash}
              lastX={lastX}
              lastY={lastY}
              alpha={alpha}
              rect={rect}
              fillStatus={clickedRect?.item_no === rect?.item_no}
              imageId={imageType === 'table' ? displayedTable?.img_id : displayedFigure?.img_id}
              imageType={imageType}
              onClickRect={onClickRect}
            />
            )
          ) : null
        }
      </Layer>
    </Stage>
  );
};

我試圖控制觸摸事件長度,因為如果它是 2,這意味着它來自多點觸控,因此縮放可以激活,反之亦然。 然而,它也沒有奏效。 感謝您提前提供任何幫助。 該演示可以在https://codesandbox.io/s/react-konva-zoom-webmobile-demo-em5o6上找到。

您的沙盒代碼中的問題似乎與這部分有關:

if (stage.isDragging()) {
    stage.stopDrag();
  }

首先,它正在檢查是否正在拖動 STAGE,而不是圖像。 但即使我們將舞台設置為可拖動並開始拖動它,此檢查仍將返回 FALSE,因為我認為它完成得太早了。

一種解決方案是添加一個新的 state 標志,例如 isZooming 並在注冊多點觸控時將其設置為 TRUE。 然后我們可以將onDragStart添加到圖像道具並在句柄 function 中,如果 isZooming 為 TRUE,我們運行stage.stopDrag()

這是您的沙盒示例的修改版本:

https://codesandbox.io/s/react-konva-zoom-webmobile-demo-forked-mb1pg?file=/src/components/generic-canvas.jsx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM