I am trying to use canvas in React. 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.
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
You need to set width and height as html properties:
<canvas ref={this.canvasRef} width={this.state.canvasWidth} height={this.state.canvasHeight}/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With