【问题标题】:How to get correct width and height for a canvas in react?如何在反应中为画布获得正确的宽度和高度?
【发布时间】:2019-05-13 21:27:38
【问题描述】:

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

【问题讨论】:

    标签: reactjs canvas ref


    【解决方案1】:

    您需要将宽度和高度设置为html属性:

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

    【讨论】:

    • 对 OP 的说明:请注意这一点,因为即使使用 ref,只要通过 setState() 更改 widthheight,画布就会被清除。
    • 谢谢,这行得通。 @PatrickRoberts,您有什么建议作为更好的做法?
    • @skypen 这是一个很好的建议,只是希望您注意潜在的意外副作用。这种行为并不是唯一的反应,只是 widthheight 属性实际上是属性访问器,当它调整大小时也会清除画布。
    猜你喜欢
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多