使用React和Konva的自适应画布 [英] Responsive canvas with React and Konva

查看:205
本文介绍了使用React和Konva的自适应画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用React和Konva库画一条简单的线.但是,当我调整屏幕大小时,该行不在屏幕外.那么,如何使它具有响应能力?

I use React and Konva libraries to draw a simple line. But when i resize the screen, the line stays out of the screen. So, how can I make it responsive?

这是我的代码:

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;

推荐答案

响应逻辑"实际上取决于您的应用和所需的UI目标.您可以在此处添加响应的最简单方法是使用缩放:

The "responsive logic" really depends on your app and on your desired UI goals. The simplest way you can add responsive here is to use scaling:

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;

这篇关于使用React和Konva的自适应画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆