首页 > 解决方案 > React ComponentDidMount 内部的画布在窗口调整大小时重绘

问题描述

我有一个画布(用 p5.js 制作)。当您第一次加载页面时,画布会使用整个窗口宽度在背景中绘制。但我有一个按钮可以显示我的项目。该按钮增加窗口高度。画布不会更新以绘制额外添加的高度。没有画布的网站位于 ( https://umr.now.sh/ )。

我的问题:

在此处输入图像描述

//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

标签: javascriptreactjsgoogle-chromecanvasp5.js

解决方案


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

window.addEventListener('resize', handleResize);

这段代码应该在componentDidMount. 在您handleResize提供的函数中,您可以添加基于window.innerWidth和更新画布大小的逻辑window.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


推荐阅读