pmndrs / react-zdog

⚡️🐶 React bindings for zdog
MIT License
443 stars 21 forks source link

Add 'renderOnce' option to Illustration #13

Closed ryanrossiter closed 1 year ago

ryanrossiter commented 5 years ago

For static illustrations the canvas/svg doesn't need to be rendered every frame, page performance could be benefited if there was an option to have the Illustration render one time on mount.

I tried implementing it like this: (line 96)

const Illustration = React.memo(                        // Change here
  ({ children, style, resize, element: Element = 'svg', renderOnce = false, ...rest }) => {

...

let active = !renderOnce // And here
function render(t) {
  const { size, subscribers } = state.current
  if (size.width && size.height) {
    // Run global effects
    globalEffects.forEach(fn => fn(t))
    // Run local effects
    subscribers.forEach(fn => fn(t))
    // Render scene
    state.current.illu.updateRenderGraph()
  }
  if (active) frame = requestAnimationFrame(render)
}

// Start render loop
render()

But it doesn't render anything, even though render() is being called once. Any suggestions?

ryanrossiter commented 5 years ago

I found out why it wasn't rendering anything when render is called once right away: The illustration starts with dimensions of 0x0 and then later receives its actual dimensions, so the first render will never show anything.

To resolve this, I added a condition in the resize handler to also call render if renderOnce is set. This results in the illustration only being rendered when it's resized.