响应式画布与React和Konva

时间:2018-04-20 14:16:56

标签: javascript reactjs line responsive konvajs

我使用React和Konva库来绘制一条简单的线。但是当我调整屏幕大小时,线条会停留在屏幕之外。那么,我怎样才能使其响应?

这是我的代码:

import React from "react";
import { Stage, Layer,Line } from 'react-konva';

class App extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
        <div>
            <Stage width={window.innerWidth} height={window.innerHeight}>
                <Layer>
                    <Line
                        x={100}
                        y={100}
                        points={[0,0,576,456,509,403,20,15,300,207,111,222,293,177]}
                        stroke="black"
                        strokeWidth={5}
                        ref="line"
                    />
                </Layer>
            </Stage>
        </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:3)

响应逻辑&#34;真的取决于您的应用程序和您期望的UI目标。您可以在此处添加响应的最简单方法是使用缩放:

import React from "react";
import { Stage, Layer,Line } from 'react-konva';

class App extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    // lets think you want to make all your objects visible in
    // 700x700 scene
    const CANVAS_VIRTUAL_WIDTH = 700;
    const CANVAS_VIRTUAL_HEIGHT = 700;

    // now you may want to make it visible even on small screens
    // we can just scale it
    const scale = Math.min(
      window.innerWidth / CANVAS_VIRTUAL_WIDTH,
      window.innerHeight / CANVAS_VIRTUAL_HEIGHT
    );

    return (
        <div>
            <Stage width={window.innerWidth} height={window.innerHeight} scaleX={scale} scaleY={scale}>
                <Layer>
                    <Line
                        x={100}
                        y={100}
                        points={[0,0,576,456,509,403,20,15,300,207,111,222,293,177]}
                        stroke="black"
                        strokeWidth={5}
                        ref="line"
                    />
                </Layer>
            </Stage>
        </div>
    );
  }
}

export default App;