【问题标题】:How can I switch the y-axis in the Konva.js stage to start from bottom to top instead of top to bottom?如何在 Konva.js 阶段切换 y 轴以从下到上而不是从上到下开始?
【发布时间】:2020-07-07 22:54:22
【问题描述】:

我想绘制笛卡尔坐标系中的数据。原点 (0/0) 从左下角开始。在 HTML-canvas 中,原点位于左上角。如何切换 y 轴(在 react-konva 或 konva 中)?

function App() {
  const points = [0, 0, 400, 400];

  return (
    <div className="App">
      <Stage width={window.innerWidth} height={window.innerHeight}>
        <Layer>
          <Line points={points} stroke="red" strokeWidth={10} />
        </Layer>
      </Stage>
    </div>
  );
}

作为示例,提供的代码从左上角向中心绘制一条线。我想通过切换y轴从左下角开始。

一切顺利,斯特凡

【问题讨论】:

    标签: konvajs react-konva


    【解决方案1】:

    方式一:使用负比例Y

    第一种方法是用scaleY={-1} 翻转y 轴。另外,您需要更改舞台的y,以便内容可见。

    function App() {
      const points = [0, 0, 400, 400];
    
      return (
        <Stage
          width={window.innerWidth}
          height={window.innerHeight}
          scaleY={-1}
          y={window.innerHeight}
        >
          <Layer>
            <Line points={points} stroke="red" strokeWidth={10} />
          </Layer>
        </Stage>
      );
    }
    

    但是你应该小心这种方法,这意味着所有的图纸都会被翻转。因此,如果您在舞台上有文字,它也会被反转。

    https://codesandbox.io/s/react-konva-revert-y-axis-ldqgd

    方式2:手动计算位置:

    function invertPoints(points, height = window.innerHeight) {
       return points.map((value, index) => {
          // ignore `x` coordinate change
          if (index % 2 === 0) {
             return value;
          }
          //
          return height - value;
       });
    }
    
    function App() {
      const points = invertPoints([0, 0, 400, 400], window.innerHeight);
    
      return (
        <Stage
          width={window.innerWidth}
          height={window.innerHeight}
        >
          <Layer>
            <Line points={points} stroke="red" strokeWidth={10} />
          </Layer>
        </Stage>
      );
    }
    

    https://codesandbox.io/s/react-konva-revert-y-axis-manually-0lwiv?file=/src/index.js

    【讨论】:

    • 您是否考虑过添加一个功能来翻转图层的轴?这样,形状/绘图点可以在翻转层上反向绘制,文本可以在非翻转层上输出。如果您正在考虑它,那么对于文本定位,在任一层上的任何点之间进行转换会很棒。这不是必须的,甚至不是非常可取的,因为那里有很多图表库!
    • 正是我需要的。谢谢!我想我会选择选项 1,但选项 2 也很有趣。两种选择都很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2013-03-12
    • 2019-11-18
    相关资源
    最近更新 更多