【问题标题】:React canvas context.fillRect doesn't work反应画布 context.fillRect 不起作用
【发布时间】:2021-07-06 11:37:22
【问题描述】:

我想用 React 画矩形, 下面有什么问题吗?

我不明白为什么这段代码不画一个矩形。


class GameView{
    constructor(props) {
        this.canvas = React.createRef()
        this.width = 0;
        this.height = 0;

        this.canvas_style = {
            width: 600,
            height: 400
        }

    }

    componentDidMount() {
        this.width = document.body.offsetWidth;
        this.height = document.body.offsetHeight;

        this.canvas_style = {
            width: this.width,
            height: this.height
        }

        this.context = this.canvas.current.getContext("2d");
    }

    render() {
        return (
            <canvas id="game-view" ref={this.canvas} width={this.width} height={this.height} />
        )
    }
}
class View extends GameView {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        super.componentDidMount();
        this.context.fillStyle =  "black";
        this.context.fillRect(0, 0, 200, 200)
    }

    render() {
        return (
            <canvas id="game-view" ref={this.canvas} width={this.width} height={this.height} style={this.canvas_style} />
        )
    }
}

我尝试了 docment.getElementById("game-view") 但得到了相同的结果

【问题讨论】:

    标签: javascript reactjs canvas html5-canvas jsx


    【解决方案1】:

    GameView 需要扩展 React.Component,所以 React 可以渲染它。

    容器的高度(在这种情况下为body)需要大于0,所以canvas会有一些高度。

    View 不需要渲染不同的 JSX:

    class GameView extends React.Component {
      canvas = React.createRef()
      width = document.body.offsetWidth;
      height = document.body.offsetHeight;  
      
      componentDidMount() {
        this.context = this.canvas.current.getContext("2d");
      }
    
      render() {
        return (
          <canvas id="game-view" ref={this.canvas} width={this.width} height={this.height} />
        )
      }
    }
    
    class View extends GameView {
      componentDidMount() {
        super.componentDidMount();
        this.context.fillStyle = "black";
        this.context.fillRect(0, 0, 200, 200)
      }
    }
    
    ReactDOM.render(
      <View />,
      root
    );
    html, body {
      margin: 0;
      height: 100%;
    } 
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    
    <div id="root"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 2016-04-27
      相关资源
      最近更新 更多