猿问

如何在 react-konva 上重置拖动画布的位置?

我有一个 react konva 项目,您可以在其中将图像加载到画布中,然后四处拖动画布。如果您加载不同的图像,则它会出现在上一张图像被拖动到的位置。我猜是否有任何方法可以重置舞台上的这个“拖动”位置(可拖动组件)。由于我正在使用反应,我唯一能想到的就是重新渲染整个组件,这现在不是问题,但我想有替代方案。


我之所以让舞台而不是图像本身可拖动,是因为我有一系列想要与图像一起移动的点。当然,我可以将点和图像都添加到组中,但这会引入一些可能不值得的复杂性。


我现在拥有的代码如下所示:


  <Stage draggable width={canvasWidth} height={canvasHeight}>

        <Layer ref={layerRef}>

          {imageInfo.loaded && (

            <Image

              image={image}

              onClick={addPoint}

              onTap={addPoint}

              width={imageInfo.targetWidth}

              height={imageInfo.targetHeight}

            />

          )}

          {points.map((p, idx) => (

            <Circle

              key={pointId(p)}

              x={p.x}

              y={p.y}

              fill={color}

              radius={size}

              onClick={() => setPoints(points => removePos(idx, points))}

            />

          ))}

        </Layer>

      </Stage>


达令说
浏览 235回答 1
1回答

皈依舞

如果您想在加载新图像时重置舞台位置,您可以:ref如果访问,请手动重置舞台的位置const App = () => {&nbsp; const stageRef = React.useRef();&nbsp; const [image] useImage(url);&nbsp; // every time an images is changed we should reset position of the stage&nbsp; React.useEffect(() => {&nbsp; &nbsp; &nbsp;stageRef.current.position({ x: 0, y: 0});&nbsp; }, [image])&nbsp; return <Stage ref={stageRef} draggable width={canvasWidth} height={canvasHeight} />;};或者您可以重置状态中的位置(并且保存位置更改dragmove或dragend事件很重要):const App = () => {&nbsp; const [pos, setPos] = React.useState({x : 0, y: 0 });&nbsp; const handleDragEnd = (e) => {&nbsp; &nbsp; &nbsp;setPos({&nbsp; &nbsp; &nbsp; &nbsp;x: e.target.x(),&nbsp; &nbsp; &nbsp; &nbsp;y: e.target.y(),&nbsp; &nbsp; &nbsp;});&nbsp; };&nbsp; // every time an images is changed we should reset position of the stage&nbsp; React.useEffect(() => {&nbsp; &nbsp; &nbsp;setPos({ x: 0, y: 0});&nbsp; }, [image])&nbsp; return <Stage onDragEnd={handleDragEnd} draggable width={canvasWidth} height={canvasHeight} />;};
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答