Creating this series
In the world of 3d development, the classic "Hello World" program generally involves rendering a cube. Let's create one ourselves using React Three Js and React Three Fiber.
Creating a cube is fairly simple with react three fiber and react three drei but we will first setup our scene before rendering any of the geometry or meshes.
If terms like Meshes, geometry, and scene sound unfamiliar, fear not! Before diving in, we recommend checking out this helpful resource also: What is ThreeJS and ReactThree Fiber
Let's get started with setting up our scene
import { OrbitControls } from "@react-three/drei";
import { Canvas } from "@react-three/fiber";
export default function App() {
return (
<div style={{ height: "100vh", width: "100vw" }}>
<Canvas>
<OrbitControls />
<gridHelper />
</Canvas>
</div>
);
}
Scene Setup
Canvas
- This is the essential component for most React Three Fiber applications. It acts as a container, providing context for other Three.js components like lights, cameras, and meshes. It also renders the HTMLcanvas
element where your 3D graphics are displayed and updates it for animationsOrbitControls
- This component allows you to explore the scene using your mouse, similar to how a camera can pan, zoom, and rotate around a physical space. We're using it with gridHelper for beginners to visualize the scene layout easily.gridHelper
- It helps to generate a grid of lines with specified dimensions which helps us to visualize the scale of the scene by providing reference points.
You should now see a gray line in the browser. If you move your mouse while clicking, you'll see the entire grid appear.
Rendering The Cube
Now, let's render the cube using BoxGeometry from Three.js and meshBasicMaterial to define its color.
import { ..., Box } from "@react-three/drei";
export default function App() {
return (
<div style={{ height: "100vh", width: "100vw" }}>
<Canvas>
...
<Box>
<meshBasicMaterial color="orange" />
</Box>
</Canvas>
</div>
);
}
Box
: This component from @react-three/drei is a simple wrapper around Three.js's BoxGeometry. Geometry defines the shape of an object using sets of point coordinates.meshBasicMaterial
: This is a basic material provided by Three.js. Materials describe the visual properties of a geometry's faces, including color, opacity, and more.
Congratulations, we have just rendered our first 3d scene.🎉🎉🎉
Next Step: Let's learn to rotate the cube
Top comments (0)