How to interact with three-fiber components

mitrich
2 min readAug 14, 2023

--

Last six months I’m actively developing my skills in software development myself and at the RSSchool course.

This month set a difficult goal — to learn React, Bootstrap, and Three.js with developing my new pet project in parallel with the final project on the course. Nowadays I work as a swimming pool engineer so my plan included developing a web application for calculating pool parameters and rendering basic swimming pool 3D model.

I started to study react three-fiber without deep knowledge of the classic three.js library and it wasn’t a good idea.
Three.js has a lot of geometry models, but for my purpose, I need to work with triangles, because pools have variable depth. That’s why I chose BufferGeometry.

After initial success, I ran into problems with updating the geometry of Meshes. If you pass the new size to CubeGeometry it works by itself — mesh resizes and changes its position. But if you do the same with BufferGeometry and BufferAtribute it remains the same.

I am stuck in this problem because of a lack of knowledge of both React and Three.js. And it wasn’t easy for me to google the right way to resolve this.
The answer was simple enough, this example of code describes it:

function TriangleMesh() {
const meshRef = useRef<three.Mesh>(null);
useFrame(() => {
if (meshRef.current) {
const newGeometry = new Float32Array([
-1.0, -1.0, 1.0, // vertex 1
1.0, -1.0, 1.0, // vertex 2
1.0, 1.0, 1.0, // vertex 3
]);
const newAttribute = new three.BufferAttribute(newGeometry, 3);
meshRef.current.geometry.setAttribute(‘position’, newAttribute);
}
});
return (
<mesh ref={meshRef}>
<bufferGeometry >
<bufferAttribute args={[initialGeometry, 3]} />
</bufferGeometry>
<meshBasicMaterial color={‘red’} side={three.DoubleSide} />
</mesh>
);
}

useRef hook allows you to connect your React component to a classic variable, and use it later with a three-fiber useFrame hook, which executes each time before rendered frame.

This way you can change mesh parameters.
Another confirmation to study the basics first.

--

--

mitrich

geophysics => construction & design => IT | Getting into web development - better today than never.