reactjs - 如何在滚动上 react konva 缩放

标签 reactjs canvas konvajs

您好,我正在尝试在我的 react 项目中的矩形上实现缩放功能,但找不到以 react 方式实现的方法?有什么帮助吗?

这是我找到的 html konva 示例:
https://konvajs.github.io/docs/sandbox/Zooming_Relative_To_Pointer.html

最佳答案

import React, { Component } from 'react';
import Konva from 'konva';
import { render } from 'react-dom';
import { Stage, Layer, Circle } from 'react-konva';

class App extends Component {
  state = {
    stageScale: 1,
    stageX: 0,
    stageY: 0
  };
  handleWheel = e => {
    e.evt.preventDefault();

    const scaleBy = 1.02;
    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 * scaleBy : oldScale / scaleBy;


    this.setState({
      stageScale: newScale,
      stageX:
        -(mousePointTo.x - stage.getPointerPosition().x / newScale) * newScale,
      stageY:
        -(mousePointTo.y - stage.getPointerPosition().y / newScale) * newScale
    });
  };
  render() {
    return (
      <Stage
        width={window.innerWidth}
        height={window.innerHeight}
        onWheel={this.handleWheel}
        scaleX={this.state.stageScale}
        scaleY={this.state.stageScale}
        x={this.state.stageX}
        y={this.state.stageY}
      >
        <Layer>
          <Circle
            x={window.innerWidth / 2}
            y={window.innerHeight / 2}
            radius={50}
            fill="green"
            shadowBlur={5}
          />
        </Layer>
      </Stage>
    );
  }
}

render(<App />, document.getElementById('root'));

演示:https://codesandbox.io/s/react-konva-zoom-on-scroll-demo-9t7ks

关于reactjs - 如何在滚动上 react konva 缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52054848/

相关文章:

konvajs - 通过在konva中的对象周围画一个框来选择

javascript - 在 ImmutableJS 中更新列表中的对象

javascript - 如何在调整大小时提高 Konva 调整大小的性能

javascript - 将多个 imageData 结构合并到一张 Canvas 中

android - 将 Canvas 内的游戏对象移动到接触点

javascript - 使用百分比而不是像素会更改 html 5 Canvas 会更改其属性吗?

javascript - Mobile 上的 Safari 阻止 window.open

javascript - Axios 发布为 JSON 对象,如何更改

reactjs - formik-material-ui 不适用于 ToggleButtonGroup 组件

reactjs - 在Next.js 13应用程序目录中,如何增量生成新页面?