[英]How to get correct width and height for a canvas in react?
I am trying to use canvas in React. 我正在尝试在React中使用canvas。 the following code is supposed to give me a black 800x800 canvas, but for some reason it ignores my dimensions and shows a 300x150 canvas.
以下代码应该给我黑色的800x800画布,但是由于某种原因,它会忽略我的尺寸并显示300x150的画布。
import React, {Component} from "react";
class Sample extends Component {
state = {
canvasWidth: 800,
canvasHeight: 800
}
canvasRef = React.createRef();
componentDidMount() {
const canvas = this.canvasRef.current;
const context = canvas.getContext('2d');
context.fillRect(0, 0, this.state.canvasWidth, this.state.canvasHeight);
}
render() {
return (
<div>
<canvas ref={this.canvasRef} />
</div>
);
}
}
export default Sample
您需要将width和height设置为html属性:
<canvas ref={this.canvasRef} width={this.state.canvasWidth} height={this.state.canvasHeight}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.