【发布时间】: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