p5js resizeCanvas 不是调整大小的函数
p5js resizeCanvas is not a function on resize
我正在使用 react-p5。我正在尝试在 window 大小更改时调整 canvas 的大小。我尝试通过添加一个调整大小事件侦听器并在每次调整浏览器大小时调用一个函数来做到这一点。
代码:
useEffect(() => {
window.addEventListener("resize", windowResized);
return () => window.removeEventListener("resize", windowResized);
});
// Canvas Setup
const setup = (p5, canvasParentRef) => {
p5.createCanvas(window.innerWidth, window.innerHeight).parent(canvasParentRef)
}
function windowResized(p5) {
p5.resizeCanvas(window.innerWidth, window.innerHeight);
}
// Main App
<Sketch setup={setup} draw={draw} />
问题是当我调整浏览器大小时我得到:Uncaught TypeError: p5.resizeCanvas is not a function at windowResized。我读到一个不同的问题,它说其他 p5 函数仅在 setup()
之后对 运行 可用,但这是我第一次使用 p5js,所以我不确定这是否是问题所在。谢谢
一个简单的解决方案是在 setup
函数中将 p5
分配给组件状态,然后您可以稍后使用。想法草案如下所示:
const App = () => {
const [p5, setP5] = useState();
// Just register event as mounted
useEffect(() => {
window.addEventListener("resize", windowResized);
return () => window.removeEventListener("resize", windowResized);
}, []);
const setup = (p5, canvasParentRef) => {
// set to state
setP5(p5)
p5.createCanvas(window.innerWidth, window.innerHeight).parent(canvasParentRef)
}
function windowResized() {
// keep in mind, `p5` can be `undefined`
// so check it before using
if (p5) {
p5.resizeCanvas(window.innerWidth, window.innerHeight);
}
}
return <Sketch setup={setup} draw={draw} />
}
我正在使用 react-p5。我正在尝试在 window 大小更改时调整 canvas 的大小。我尝试通过添加一个调整大小事件侦听器并在每次调整浏览器大小时调用一个函数来做到这一点。
代码:
useEffect(() => {
window.addEventListener("resize", windowResized);
return () => window.removeEventListener("resize", windowResized);
});
// Canvas Setup
const setup = (p5, canvasParentRef) => {
p5.createCanvas(window.innerWidth, window.innerHeight).parent(canvasParentRef)
}
function windowResized(p5) {
p5.resizeCanvas(window.innerWidth, window.innerHeight);
}
// Main App
<Sketch setup={setup} draw={draw} />
问题是当我调整浏览器大小时我得到:Uncaught TypeError: p5.resizeCanvas is not a function at windowResized。我读到一个不同的问题,它说其他 p5 函数仅在 setup()
之后对 运行 可用,但这是我第一次使用 p5js,所以我不确定这是否是问题所在。谢谢
一个简单的解决方案是在 setup
函数中将 p5
分配给组件状态,然后您可以稍后使用。想法草案如下所示:
const App = () => {
const [p5, setP5] = useState();
// Just register event as mounted
useEffect(() => {
window.addEventListener("resize", windowResized);
return () => window.removeEventListener("resize", windowResized);
}, []);
const setup = (p5, canvasParentRef) => {
// set to state
setP5(p5)
p5.createCanvas(window.innerWidth, window.innerHeight).parent(canvasParentRef)
}
function windowResized() {
// keep in mind, `p5` can be `undefined`
// so check it before using
if (p5) {
p5.resizeCanvas(window.innerWidth, window.innerHeight);
}
}
return <Sketch setup={setup} draw={draw} />
}