Как получить правильную ширину и высоту для холста в реакции? - PullRequest
0 голосов
/ 14 мая 2019

Я пытаюсь использовать canvas в 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

1 Ответ

2 голосов
/ 14 мая 2019

Вам необходимо установить ширину и высоту в качестве свойств html:

   <canvas ref={this.canvasRef} width={this.state.canvasWidth} height={this.state.canvasHeight}/>
...