簡體   English   中英

反應 canvas context.fillRect 不起作用

[英]React canvas context.fillRect doesn't work

我想用 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") 但得到了相同的結果

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM