在窗口调整大小时重新绘制了React ComponentDidMount内部的画布

时间:2019-06-13 17:10:56

标签: javascript reactjs google-chrome canvas p5.js

我有一块画布(由p5.js制造)。首次加载页面时,将使用整个窗口宽度在后台绘制画布。但是我有一个按钮可以显示我的项目。该按钮增加窗口高度。画布不会更新以绘制额外增加的高度。没有画布的网站位于(https://umr.now.sh/)。

我的问题:

  • 我将如何使compnentdidmount“刷新”或重新绘制画布以覆盖新的窗口大小。

  • 我是否甚至需要担心componentdidmount或p5.js是否具有某种可以帮助解决问题的功能

    enter image description here

enter image description here

//homepage.js 

class Index extends React.Component{
    constructor(){ 
        super()
        this.state = {
            isLoading: true
        }
        this.isLoaded = this.isLoaded.bind(this)
    }
    isLoaded() {
        console.log("Clicked")
        this.setState({
            isLoading: !this.state.isLoading,

        })
    }

    render(){
        let view;
        if (this.state.isLoading){
            view = <div> <Home isLoading={this.state.isLoading} isLoaded={this.isLoaded}/></div>
        } else {
            view = <div> <Project isLoading={this.state.isLoading} isLoaded={this.isLoaded}/></div>
        }
        return(
            <div className="Homepage">
                <div className="Name-social">
                    {view}
                </div>
                <div>
                <SketchLayOut />
                </div>


            </div>
        )
    }

}

export default Index

1 个答案:

答案 0 :(得分:0)

我对p5.js一无所知,但是JS中有一个事件监听器,您可以在其中监听窗口大小的变化:

window.addEventListener('resize', handleResize);

此代码应位于componentDidMount中。在提供的handleResize函数中,您可以添加逻辑,以根据window.innerWidthwindow.innerHeight更新画布的大小。像这样:

function handleResize() {
    //you would pass these values to your canvas to update the width/height
    this.setState({
       width: window.innerWidth, 
       height: window.innerHeight
    });

    //etc
}

我不确定p5.js的内部结构或代码的其他部分,因此您需要找出来更新画布。但是,这至少会获得您需要的宽度/高度值。您可能还应该确保在卸载组件时删除侦听器(这样将在componentWillUnmount中)

相关问题