Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions example/src/demos/FlushSync.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { Canvas, flushSync, useThree } from '@react-three/fiber'
import { useCallback, useRef, useState } from 'react'

const colors = ['orange', 'hotpink', 'cyan', 'lime', 'yellow', 'red', 'blue', 'purple', 'green', 'coral']

function Capture() {
const [color, setColor] = useState(colors[0])
const { gl } = useThree()
const wantToCapture = useRef(false)

const handleClick = useCallback(() => {
// Use flushSync to ensure the color is updated immediately
flushSync(() => setColor(colors[Math.floor(Math.random() * colors.length)]))
wantToCapture.current = true
}, [])

const captureScreenshot = useCallback(() => {
if (wantToCapture.current) {
wantToCapture.current = false

// Takes a screenshot of the canvas and downloads it
const link = document.createElement('a')
link.href = gl.domElement.toDataURL()
link.download = 'screenshot.png'
link.click()
}
}, [gl])

return (
<mesh onClick={handleClick} onAfterRender={captureScreenshot}>
<dodecahedronGeometry args={[1, 0]} />
<meshStandardMaterial color={color} />
</mesh>
)
}

export default function App() {
return (
<Canvas>
<ambientLight intensity={Math.PI * 0.5} />
<spotLight decay={0} position={[10, 10, 10]} angle={0.15} penumbra={1} />
<Capture />
</Canvas>
)
}
2 changes: 2 additions & 0 deletions example/src/demos/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const Portals = { Component: lazy(() => import('./Portals')) }
const ViewTracking = { Component: lazy(() => import('./ViewTracking')) }
const ChangeTexture = { Component: lazy(() => import('./ChangeTexture')) }
const WebGPU = { Component: lazy(() => import('./WebGPU')) }
const FlushSync = { Component: lazy(() => import('./FlushSync')) }

export {
AutoDispose,
Expand Down Expand Up @@ -52,4 +53,5 @@ export {
ViewTracking,
ChangeTexture,
WebGPU,
FlushSync,
}