小编sky*_*pen的帖子

如何在反应中获得画布的正确宽度和高度?

我正在尝试在 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)

canvas ref reactjs

4
推荐指数
1
解决办法
1万
查看次数


标签 统计

absolute-value ×1

canvas ×1

math ×1

python ×1

reactjs ×1

ref ×1