Sketch Component
Template components for creating sketches utilising Three.JS and TSL.
What is a Sketch Component?
These are components built specifically to get you up and running with Three.JS, TSL and React Three Fiber (R3F). They have some default uniforms and settings that are useful for quick iteration and development using your Boilerplate Project.
Under the hood, it uses a transparent MeshBasicNodeMaterial
to render the sketch to the size of the viewport (as defined by your camera).
How to use it
These are components that can be used in any R3F project, but ideal to use with your Boilerplate Project.
import { WebGPUSketch } from '@/components/sketch/webgpu_sketch'
import { Fn, vec3, screenSize, uv } from 'three/tsl'
// This is a simple placeholder node that outputs uv coordinate colors to the screen
const sketchNode = Fn(() => {
const finalColor = vec3(uv(), 1.0)
return finalColor
})
export const Sketch = () => {
// The `Fn` tsl function is used to create a node that can be used in this component
// It's technically a function, so it needs to be called to instantiate it
return <WebGPUSketch colorNode={sketchNode()} />
}
In your R3F project, you can use the WebGPUSketch component.
import { Sketch } from './sketch'
import { ScreenSizeCamera } from './screen_size_camera'
export const Scene = () => {
return (
<Canvas>
<ScreenSizeCamera makeDefault />
<Sketch />
</Canvas>
)
}
onFrame Callback
This sketch provides an onFrame
callback that can be used to update the sketch from R3F's useFrame
hook.
import { WebGPUSketch } from '@/components/sketch/webgpu_sketch'
import { Fn, vec3, screenSize, uv } from 'three/tsl'
const sketchNode = Fn(() => {
const finalColor = vec3(uv(), 1.0)
return finalColor
})
const myUniform = uniform(0.0)
// Note that the `onFrame` callback is called every frame, so you need to be careful with the performance of your sketch.
const onFrame = (node, state) => {
// Do something with your node, or using R3F's full state
myUniform.value += state.clock.getElapsedTime()
}
export const Sketch = () => {
return <WebGPUSketch colorNode={sketchNode()} onFrame={onFrame} />
}
Keep in mind that this is not really the way that we'd update a time
uniform in TSL, as it provides a time
node by default.