2021年4月10日星期六

React canvas context.fillRect doesn't work

I'd like to draw rect with React, is there anything wrong in the following?

I don't figure out why this code doesn't draw a rect.

  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} />          )      }  }  

I tried docment.getElementById("game-view") but I got the same result

https://stackoverflow.com/questions/67040595/react-canvas-context-fillrect-doesnt-work April 11, 2021 at 09:06AM

没有评论:

发表评论