Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get correct width and height for a canvas in react?

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
like image 573
skypen Avatar asked Oct 15 '25 02:10

skypen


1 Answers

You need to set width and height as html properties:

   <canvas ref={this.canvasRef} width={this.state.canvasWidth} height={this.state.canvasHeight}/>
like image 63
Auskennfuchs Avatar answered Oct 17 '25 16:10

Auskennfuchs