微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React-konva 移动缩放和可拖动图像

如何解决React-konva 移动缩放和可拖动图像

我正在使用 Konva.js 构建一个画布应用程序。此应用程序允许用户拖动图像并在任何点进行缩放。这在桌面上完美运行。但是,我喜欢这个应用程序能够响应移动设备。这里的问题是画布缩放和图像拖动不能同步工作。由于“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,因为我认为它完成得太早了。

一种解决方案是添加一个新的状态标志,例如 isZooming 并在注册多点触控时将其设置为 TRUE。然后我们可以将 onDragStart 添加到图像道具中,如果 isZooming 为 TRUE,我们在句柄函数中运行 stage.stopDrag()

这是您的沙箱示例的修改版本:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。