-
Hi! What's the correct way to pass a width and height prop to the wrapper to use in I got something working using Minimal example: "use client"
import { type Sketch } from "@p5-wrapper/react"
import { NextReactP5Wrapper } from "@p5-wrapper/next"
import { useEffect, useState, useRef } from "react"
interface IProps {
containerWidth: number
}
const sketch: Sketch = (p5) => {
let containerWidth = 0
p5.setup = () => p5.createCanvas(600, 400, p5.WEBGL)
p5.updateWithProps = (props: IProps) => {
if (props.containerWidth) {
containerWidth = props.containerWidth
}
p5.resizeCanvas(containerWidth, containerWidth / 2.35)
}
p5.draw = () => {
p5.background(246)
}
}
export default function Page() {
const containerRef = useRef<HTMLDivElement>(null)
const [containerWidth, setContainerWidth] = useState(100)
useEffect(() => {
const updateContainerWidth = () => {
if (containerRef.current) {
setContainerWidth(containerRef.current.getBoundingClientRect().width)
}
}
updateContainerWidth()
const handleResize = () => {
updateContainerWidth()
}
window.addEventListener("resize", handleResize)
return () => {
window.removeEventListener("resize", handleResize)
}
}, [])
return (
<div style={{width: '100%', height: `${containerWidth / 2.35}px`, backgroundColor: 'red'}} ref={containerRef}>
<NextReactP5Wrapper sketch={sketch} containerWidth={containerWidth} />
</div>
)
}
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 9 replies
-
Hi @hanhanxue, I'm wondering if you can write an expression to calculate the canvas dimensions inside the sketch function. You probably don't need a div element around the React component, as the size of the canvas can be controlled within it. For example: const P5Canvas = () => {
const sketch = (p5) => {
const canvasWidth = ...;
const canvasHeight = ...;
p5.setup = () => {
p5.createCanvas(canvasWidth, canvasHeight);
...
} Will that be enough to achieve what you want? |
Beta Was this translation helpful? Give feedback.
-
@hanhanxue As I understand, you would like to render a few sketches of the grid size, right? |
Beta Was this translation helpful? Give feedback.
How about using JS to get the size of the container?
and after use
Then you can pass these values to the P5Canvas component and use them when creating a sketch.
In any case, your approach seems like over-engineering to me. I found some examples on stackoverflow of how to do this in plain JS, so try exploring the issue further. In my opinion, it has nothing to do with the need to pass values inside the wrapper. They should be calculated when the sketch is created.