sky*_*pen 4 canvas ref reactjs
我正在尝试在 React 中使用画布。下面的代码应该给我一个黑色的 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
Run Code Online (Sandbox Code Playgroud)
您需要将宽度和高度设置为 html 属性:
<canvas ref={this.canvasRef} width={this.state.canvasWidth} height={this.state.canvasHeight}/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11201 次 |
| 最近记录: |