如何使用 konvajs 反应中的按钮放大和缩小 canvas

How to zoom in and zoom out on canvas using button in konvajs react

我想 canvas 通过按钮的 onclick 函数放大和缩小 我已经通过 onwheel 实现了,但是无法通过按钮实现,请帮忙 https://codesandbox.io/s/react-canvas-n779q2?file=/src/App.js

function App() {
  const stageRef = useRef(null);
  const width = 500;
  const height = 500;

  const [stage, setStage] = useState({
    scale: 1,
    x: 0,
    y: 0
  });

  const scaleRelativeToPoint = (point, increaseScale) => {
    const scaleBy = 1.02;
    const stage = stageRef.current;
    const oldScale = stage.scaleX();
    const mousePointTo = {
      x: point.x / oldScale - stage.x() / oldScale,
      y: point.y / oldScale - stage.y() / oldScale
    };

    const newScale = increaseScale ? oldScale * scaleBy : oldScale / scaleBy;

    setStage({
      scale: newScale,
      x: (point.x / newScale - mousePointTo.x) * newScale,
      y: (point.y / newScale - mousePointTo.y) * newScale
    });
  };

  const handleWheel = (e) => {
    e.evt.preventDefault();
    scaleRelativeToPoint(
      e.target.getStage().getPointerPosition(),
      e.evt.deltaY < 0
    );
  };
  return (
    <>
      <Header />
      <Container fluid>
        <Row>
          <Col xs={9}>
            <Row className="">
              <Button
                variant="primary"
                onClick={() => {
                  scaleRelativeToPoint(
                    // zoom relative to center of the screen
                    {
                      x: width / 2,
                      y: height / 2
                    },
                    true
                  );
                }}
              >
                +
              </Button>{" "}
              <Button
                variant="secondary"
                onClick={() => {
                  scaleRelativeToPoint(
                    // zoom relative to center of the screen
                    {
                      x: width / 2,
                      y: height / 2
                    },
                    false
                  );
                }}
              >
                -
              </Button>{" "}
            </Row>
            <Row className="d-grid justify-content-center canvasborder">
              {/* //artboard */}
              <Stage
                className="mt-5 ml-5"
                width={width}
                height={height}
                onWheel={handleWheel}
                scaleX={stage.scale}
                scaleY={stage.scale}
                x={stage.x}
                y={stage.y}
                ref={stageRef}
              >
                <Layer>
                  <Rect fill="Blue" height={500} width={500} />
                </Layer>
              </Stage>
            </Row>
          </Col>
        </Row>
      </Container>
    </>
  );
}

演示:https://codesandbox.io/s/react-canvas-forked-910kdh?file=/src/App.js:343-2909