javascript - 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
解决方案
我对 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
)
推荐阅读
- javascript - Angular - 提交时订阅测试服务
- android-bluetooth - Android x86 禁用 USB 设备或驱动程序或选择蓝牙设备?
- svg - 重置 svg 模式原点
- npm - npm安装的“yarn add global”更新包可以吗?
- python - 根据其他列修改数据框列中的值
- typescript - 如何优雅地初始化 TypeScript 中的一系列对象?
- mysql - char_length() 和 character_length() 有什么区别
- python - 如何获取最大列值计数
- amazon-web-services - 如何通过cloudformation添加密码参数字段而不显示值?
- java - XML 存在时不存在