In this post we are going to take our first steps with Three.js —the most popular 3D JavaScript library for the web— by creating a simple scene with several types of geometric figures. The cube, which is the favorite shape in modeling software like Blender, will be our first primitive; to render it properly we need to complete three fundamental steps.
Fundamental elements in Three.js
To render any object in Three.js we need at least three elements that will always appear together in any project:
- The camera is the eye or viewpoint from which we observe the scene. It can be configured in several ways depending on the project's needs, but the most common is the perspective camera (
PerspectiveCamera), which mimics human vision and allows us to perceive depth. - The scene (
Scene) is the virtual space or universe where we place all our objects. You can imagine it as an infinite three-dimensional canvas: an empty space where our figures, lights, and other elements will exist. - Geometric figures are the objects we want to visualize. To each one we can apply animations, geometric transformations (translation, rotation, scaling), colors, and materials.
There is a fourth equally essential element: the renderer (WebGLRenderer), which acts as the graphics engine that processes all the 3D information and draws it onto a canvas element inside the HTML page. Without it, none of the above would be visible.
Preparing the work environment
Before writing a single line of Three.js we need to have Node.js installed on our system. With Node we have the npm package manager, which lets us install libraries professionally instead of downloading files manually.
We open the terminal in the project folder and run:
$ npm init -y
$ npm install three
$ npm install --save-dev viteThe first command creates the package.json file with default values. The second installs Three.js as a project dependency. The third installs Vite, a modern development server that automatically refreshes the browser every time we save a change, without needing to reload the page manually.
Once the dependencies are installed, we create the project folder structure:
mi-proyecto/
├── js/
│ └── three.js ← librería (o importada vía npm)
└── index.htmlRegardless of the method you use to load the library, when opening the browser a completely blank page should appear with no errors in the developer console (F12). That clean state indicates that everything is properly configured and we can start building.
Creating our first geometric figure: a cube
To render any 3D graphic in Three.js we need the essential triad we already mentioned. Let's see how each element translates into code:
- Scene (
Scene): the universe or empty space where we will place all objects. It is the three-dimensional canvas we work on. - Camera (
Camera): the eye or observer looking inside that universe. Without a camera we cannot see anything at all. - Renderer (
Renderer): the engine that mathematically processes the scene and draws it onto acanvaselement inside our HTML page.
Below is the minimal example to create a scene in Three.js: scene, camera, renderer, and a geometric figure. This is the starting point for any project:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="js/three.js"></script>
<script>
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 80, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ffff } );
const cube = new THREE.Mesh( geometry, material );
cube.position.y = 1
scene.add( cube );
camera.position.z = 2;
renderer.render(scene, camera);
</script>
</body>
</html>Explanation of the code above
We break down the code by blocks to understand what each part does.
First we create the renderer and tell it to occupy the entire browser window:
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );Then we insert it into the DOM so it is visible on the page:
document.body.appendChild( renderer.domElement );We create the scene and the perspective camera. The four parameters of PerspectiveCamera are: field of view in degrees (fov), aspect ratio, near clipping plane, and far clipping plane:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 80, window.innerWidth / window.innerHeight, 0.1, 1000 );We create the cube's geometry with BoxGeometry:
const geometry = new THREE.BoxGeometry();And we assign it a material. MeshBasicMaterial is the simplest one: it does not react to light and only displays the color we specify:
const material = new THREE.MeshBasicMaterial( { color: 0x00ffff } );We position the cube on the Y axis so it isn't at the exact origin:
cube.position.y = 1We add it to the scene:
scene.add( cube );We move the camera back along the Z axis so it isn't inside the cube (the default origin is 0,0,0 for both):
camera.position.z = 2;And finally we trigger the render:
renderer.render(scene, camera);With this we already have a simple scene like the one shown on the cover of this post.
Creating a mesh or wireframe
The wireframe shows only the skeleton of triangles that forms a shape, without filling its faces. It is very useful during development to understand the internal structure of objects and debug positioning. In Three.js we can easily enable it on any material by adding the wireframe: true option.
Starting from a basic mesh for a cube:
const geometry = new THREE.BoxGeometry(4,4,4)
const material = new THREE.MeshBasicMaterial({ color: 0x00FF00})We just have to add wireframe: true to the material. This mode is available for virtually all Three.js geometries:
const geometry = new THREE.BoxGeometry(4,4,4)
const material = new THREE.MeshBasicMaterial({ color: 0x00FF00, wireframe: true })The rest does not change: we create the Mesh and add it to the scene:
const cube = new THREE.Mesh( geometry, material )
scene.add( cube )Creating a sphere
Three.js offers a wide catalog of primitive geometries. To draw a sphere we use SphereGeometry, which takes the radius and the number of width and height segments as required arguments. The higher the number of segments, the smoother and rounder the sphere will appear (though also more expensive to render):
THREE.SphereGeometry(20, 20, 20);The flow is identical to the cube: we define the geometry, assign it a material, and add it to the scene:
var sphereGeometry = new THREE.SphereGeometry(20, 20, 20);
var sphereMaterial = new THREE.MeshBasicMaterial({
color: 0x7777FF,
wireframe: true
});
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.set(20, 4, 2);
scene.add(sphere);Applying rotations to geometric figures
In Three.js rotations are not expressed in degrees but in radians, and to work with them we use JavaScript's Math.PI constant. The equivalence is easy to memorize:
Math.PI * 2→ full 360° rotationMath.PI→ half turn of 180°Math.PI * 0.5→ quarter turn of 90°Math.PI * 0.25→ eighth turn of 45°
The sign of the value controls the direction: positive rotates one way, negative the opposite way. In the following example we rotate a cube 90° around the X axis:
cube.rotation.x = Math.PI * .5Creating a plane
To create a plane we use PlaneGeometry, which takes the width and length of the surface as parameters. Just like with the sphere, the only thing that changes compared to the cube is the geometry class name; the creation flow is exactly the same:
const geometryPlane= new THREE.PlaneGeometry(14, 5)We define the material and add it to the scene:
// plano
const geometryPlane= new THREE.PlaneGeometry(14, 5)
const materialPlane= new THREE.MeshBasicMaterial({ color: 0xFF0000, wireframe: false })
const plane= new THREE.Mesh( geometryPlane, materialPlane)
scene.add(plane)An important detail: by default the plane appears vertical, facing the camera, as if it were a wall. To turn it into a floor we must rotate it -90° around the X axis and then lower its Y position. Once the plane is added you can apply any geometric transformation to it, for example:
//*** POSICIONES
cube.position.x = -5
cube.rotation.x = Math.PI * .5
plane.rotation.x = Math.PI * -0.5
plane.position.set(0,-2,1)Generating a Cartesian axis with AxesHelper
When working in a three-dimensional space it is easy to lose track of axis orientation. Three.js includes AxesHelper precisely for this: it draws three colored lines starting from the origin and pointing along each axis, making it an essential tool during development:
- Red → X axis (width, left-right)
- Green → Y axis (height, up-down)
- Blue → Z axis (depth, front-back)
const axesHelper = new THREE.AxesHelper( 10 );
scene.add( axesHelper );The numeric parameter indicates the length of each line. AxesHelper is a development helper that should be removed before publishing the project to production, as it adds nothing to the final result.
Comparing Three.js with 3D tools like Blender
If you have ever used modeling software like Blender or engines like Unity, you will find that Three.js's architecture is practically identical. In all these tools there is:
- A space or universe (the scene) with X, Y, and Z axes where objects are placed.
- Geometric figures (primitives) like cubes, spheres, or planes that are added to that space.
- A camera that determines the angle and perspective from which the scene is observed.
- A light source (which we will see later) to illuminate materials.
- A rendering process that converts 3D information into a 2D image.
The only fundamental difference is that in Blender we drag elements with the mouse, whereas in Three.js we do the exact same thing through JavaScript code. The underlying logic is identical, making the concepts learned here directly transferable to other 3D environments.
Exercise: aligning a sphere and a cube of the same visual size
When we add multiple objects without specifying a position, they all appear at the origin (0, 0, 0) overlapping one another. To compose the scene properly we must manipulate each object's position property.
There is an important difference between geometries to keep clear: BoxGeometry defines the total size of the cube (width × height × depth), whereas SphereGeometry defines the radius, which equals half the diameter. That is why, for a cube of side 4 to occupy the same visual space as a sphere of radius 2 (diameter 4), both values must be calculated taking that relationship into account:
const geometry = new THREE.BoxGeometry(4, 4, 4) // cubo de lado 4
const geometrySphera = new THREE.SphereGeometry(2, 20, 20) // esfera de radio 2 = diametro 4
// desplazamos el cubo hacia la izquierda en el eje X
cube.position.x = -5With this both shapes end up the same visual size and separated along the X axis. We can also use the position.set(x, y, z) method to define all three coordinates in a single statement, making the code more concise:
plane.position.set(0, -2, 1)Spatial rotations
Any object in Three.js can be rotated through the rotation property, which works across all three X, Y, and Z axes. The most important thing to remember is that rotations are not expressed in degrees but in radians.
To work comfortably with radians we use JavaScript's Math.PI constant:
Math.PI * 2→ full 360° rotationMath.PI→ half turn of 180°Math.PI * 0.5→ quarter turn of 90°Math.PI * 0.25→ eighth turn of 45°
The sign of the value controls the direction: positive rotates one way, negative the opposite way.
cube.rotation.x = Math.PI * .5 // rota el cubo 90° sobre el eje X
plane.rotation.x = Math.PI * -0.5 // acuesta el plano horizontalmenteRotations also help fix visualization issues. If a cube and a sphere of the same size appear to have different dimensions when viewed from the front, a slight rotation of the cube reveals its real depth and confirms that both objects are equal.
Generating a base plane
A plane is a flat rectangular surface created with PlaneGeometry. It accepts width and height as parameters and, optionally, the number of segments along each dimension (useful if we want to deform the plane later with a shader or modifier):
// plano
const geometryPlane = new THREE.PlaneGeometry(14, 5)
const materialPlane = new THREE.MeshBasicMaterial({ color: 0xFFFF00, wireframe: true })
const plane = new THREE.Mesh(geometryPlane, materialPlane)
scene.add(plane)By default the plane appears vertical, facing the camera, as if it were a wall. To turn it into a floor or table we must lay it flat by rotating it 90° around the X axis (with a negative value) and then lower its Y position so it sits just below the other figures:
plane.rotation.x = Math.PI * -0.5 // acuesta el plano en posicion horizontal
plane.position.set(0, -2, 1) // lo desplaza hacia abajo y un poco al frenteThe result is a floor on which the cube and sphere visually rest, giving spatial context to the entire scene.
AxesHelper: visualizing coordinate axes
When working in a three-dimensional space it is easy to get confused about axis orientation. Three.js includes the AxesHelper object precisely for this: it draws three colored lines starting from the origin and pointing along each axis:
- Red → X axis (width, left-right)
- Green → Y axis (height, up-down)
- Blue → Z axis (depth, front-back)
const axes = new THREE.AxesHelper(5)
scene.add(axes)
axes.position.x = 3The numeric parameter indicates the length of each line. AxesHelper is a helper object for development that should be removed before publishing the final project.
lookAt: pointing the camera at a target
When we raise or move the camera to get an interesting angle, it can happen that it stops pointing toward the scene and we see only black. Manually calculating the exact rotation angles so the camera looks where we want is tedious and error-prone.
The lookAt() method solves this automatically: we pass it the coordinates of the point or object we want to observe and Three.js calculates all the necessary rotation angles on its own:
camera.position.z = 9
camera.position.y = 7
camera.position.x = 8
camera.lookAt(cube.position) // apunta automaticamente al cuboWe can also point at the center of the entire scene by passing scene.position, which is always the origin (0, 0, 0):
camera.lookAt(scene.position)Regardless of where the camera is located, lookAt() guarantees it will always look at the specified target, which greatly simplifies scene composition.
The complete source code
Below is the complete source code for everything we have built throughout this chapter. Each section is commented to make it easier to read:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Primeros pasos con Three.js</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="../js/three.js"></script>
<script>
// escena - universo
const scene = new THREE.Scene()
// camara u ojo
const camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight)
// renderizado
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
// agregamos el proceso del render al documento
document.body.appendChild(renderer.domElement)
// geometria, elementos poligonales y otras figuras 3D
const geometry = new THREE.BoxGeometry(4, 4, 4)
const material = new THREE.MeshBasicMaterial({ color: 0x00FF00, wireframe: true })
// cubo
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
// esfera geometria y material
const geometrySphera = new THREE.SphereGeometry(2, 20, 20)
const materialSphera = new THREE.MeshBasicMaterial({ color: 0x00FFFF, wireframe: true })
const sphera = new THREE.Mesh(geometrySphera, materialSphera)
scene.add(sphera)
// plano
const geometryPlane = new THREE.PlaneGeometry(14, 5)
const materialPlane = new THREE.MeshBasicMaterial({ color: 0xFFFF00, wireframe: true })
const plane = new THREE.Mesh(geometryPlane, materialPlane)
scene.add(plane)
const axes = new THREE.AxesHelper(5)
scene.add(axes)
//*** POSICIONES
cube.position.x = -5
cube.rotation.x = Math.PI * .5
plane.rotation.x = Math.PI * -0.5
plane.position.set(0, -2, 1)
axes.position.x = 3
camera.position.z = 9
camera.position.y = 7
camera.position.x = 8
camera.lookAt(cube.position)
// renderizar
renderer.render(scene, camera)
</script>
</body>
</html>Chapter summary
In this chapter we established the foundations on which any Three.js project is built:
- We set up the environment with Node.js and Vite for a modern workflow.
- We learned the essential triad: Scene, Camera, and Renderer.
- We created our first primitives:
BoxGeometry,SphereGeometry, andPlaneGeometry. - We enabled wireframe to understand the internal structure of meshes.
- We manipulated
positionandrotation(in radians withMath.PI) to compose the scene. - We used
AxesHelperas a visual orientation tool during development. - We simplified camera orientation with the powerful
lookAt()method.
With these tools in hand we are ready to move toward more complex scenes: animations, lighting, textures, and interactive controls that we will cover in upcoming chapters.
Source:
- https://github.com/libredesarrollo/curso-threejs-fundamentos-01/blob/main/base/esqueleto.html
- https://github.com/libredesarrollo/curso-threejs-fundamentos-01/blob/main/base/01_primeros_pasos.html
Garden Project
In this chapter we will consolidate what we learned by building a complete project from scratch: a small three-dimensional garden. The scene includes a green floor, a wooden fence that outlines the space, a tree made up of a trunk and foliage, and a house formed by a cylindrical base and a conical roof. Throughout the process we will learn new geometries, advanced positioning techniques, and —very importantly— how to organize code into reusable functions to keep it clean as it grows.
Project overview
The final goal is a scene that at first glance looks simple —almost like a child's drawing— but holds several interesting technical challenges:
- Composing objects by stacking multiple geometries (the house, the tree).
- Positioning each element properly within 3D space.
- Discovering and using new geometries:
CylinderGeometryandConeGeometry. - Organizing code into functions to keep it clean and scalable.
The final result, seen from above, shows a rectangular green plane surrounded by four brown bars forming a fence, a tree on the left, and a house on the right.
Preparing the HTML skeleton
The starting point is the same HTML skeleton from the previous chapter: a document with margin: 0 on the body, the Three.js library included, and a <script> block where we will work. We verify in the browser that a blank page appears with no console errors before adding any object.
The floor: PlaneGeometry as the garden ground
The first thing we build is the garden ground. We use a PlaneGeometry of 20 × 10 units with an intense green color. The plane initially appears upright, like a wall, so we rotate it -90° around the X axis to lay it flat horizontally and lower it slightly on Y so it serves as the ground:
function floor(scene) {
const planeGeometry = new THREE.PlaneGeometry(20, 10)
const planeMaterial = new THREE.MeshBasicMaterial({
color: 0x779922,
wireframe: false
})
var plane = new THREE.Mesh(planeGeometry, planeMaterial)
plane.rotation.x = -0.5 * Math.PI
plane.position.y = -0.5
scene.add(plane)
}Notice the use of wireframe: false: unlike the previous chapter, here we want a solid plane that simulates grass, not a wireframe skeleton. The value -0.5 * Math.PI equals -90° in radians.
The fence: reusing geometries and materials
The fence is made up of four rectangular wooden bars surrounding the garden. Here we apply a very useful pattern: the same material can be assigned to several different meshes. We create the brown material once and reuse it across all four bars, saving memory and keeping the code concise:
function bar(scene) {
const barMaterial = new THREE.MeshBasicMaterial({ color: 0x994422 })
// barras izquierda y derecha (eje Z, largo 11)
const geometryBarRightLeft = new THREE.BoxGeometry(1, 1, 11)
const barRight = new THREE.Mesh(geometryBarRightLeft, barMaterial)
barRight.position.x = 10
scene.add(barRight)
const barLeft = new THREE.Mesh(geometryBarRightLeft, barMaterial)
barLeft.position.x = -10
scene.add(barLeft)
// barras superior e inferior (eje X, largo 19)
const geometryBarUpBottom = new THREE.BoxGeometry(19, 1, 1)
const barUp = new THREE.Mesh(geometryBarUpBottom, barMaterial)
barUp.position.z = 5
scene.add(barUp)
const barBottom = new THREE.Mesh(geometryBarUpBottom, barMaterial)
barBottom.position.z = -5
scene.add(barBottom)
}Notice the positioning logic: the garden measures 20 units wide, so the origin is in the center. To place the right bar on the right edge we move it +10 on X (half the width). The left one goes to -10. The front and back bars are placed at Z = ±5 (half of the 10 depth).
You will also notice that two different geometries are defined (one for the side bars and another for the front/back bars) because their dimensions are different: the side ones are long along Z and the front ones are long along X.
The tree: composing two geometries
The tree demonstrates how to build complex objects by stacking simple primitives. It is made up of two parts:
- Trunk: a thin, tall
BoxGeometry(dark brown color). - Foliage: a low-segment
SphereGeometry(green color) placed on top of the trunk.
function tree(scene) {
// ARBOL
const trunkGeometry = new THREE.BoxGeometry(1, 8, 1)
const trunkMaterial = new THREE.MeshBasicMaterial({ color: 0x110000 })
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial)
trunk.position.y = 3
trunk.position.x = -3
scene.add(trunk)
const fodderGeometry = new THREE.SphereGeometry(4, 5, 6)
const fodderMaterial = new THREE.MeshBasicMaterial({ color: 0x00AA00 })
const fodder = new THREE.Mesh(fodderGeometry, fodderMaterial)
fodder.position.y = 9
fodder.position.x = -3
scene.add(fodder)
// FIN ARBOL
}The trunk has a height of 8, so it grows 4 units upward and 4 downward from its center. For it to start from the ground we shift it to y = 3. The foliage (radius 4) is placed at y = 9 to sit right above the tip of the trunk. Both share the same x = -3 position to align vertically.
Using few segments on the foliage sphere (5, 6) gives a faceted, cartoon-like look, completely consistent with the project's illustration style.
The house: CylinderGeometry and ConeGeometry
The house introduces two new geometries. The base is a cylinder (CylinderGeometry) and the roof is a cone (ConeGeometry). Combining both forms a stylized house with a seamless fit between the two pieces.
CylinderGeometry takes four parameters: top radius, bottom radius, height, and number of segments. Using the same radius value at top and bottom gives us a perfect cylinder:
function house(scene) {
// Base de la casa
const houseBaseGeometry = new THREE.CylinderGeometry(2, 2, 3)
const houseBaseMaterial = new THREE.MeshBasicMaterial({ color: 0xFFEECC })
const houseBase = new THREE.Mesh(houseBaseGeometry, houseBaseMaterial)
houseBase.position.y = 1
houseBase.position.x = 5
scene.add(houseBase)
// Techo en forma de cono
const houseRoofGeometry = new THREE.ConeGeometry(2, 3, 15)
const houseRoofMaterial = new THREE.MeshBasicMaterial({ color: 0x776600 })
const houseRoof = new THREE.Mesh(houseRoofGeometry, houseRoofMaterial)
houseRoof.position.y = 4
houseRoof.position.x = 5
scene.add(houseRoof)
// FIN Casa
}ConeGeometry takes: base radius, height, and number of segments. With 15 segments the cone looks round enough to resemble a roof. If we used few segments (3 or 4) the result would be a triangular or quadrangular pyramid.
Calculating heights is key so the base and roof fit without visible gaps: the base has a height of 3 and its center is at y = 1, so its top edge sits at y = 2.5. The roof is placed at y = 4 so its base starts at that same height.
Note: if we tried to use a BoxGeometry as the house base, the joint with the cone would look visually broken, since a square doesn't fit well with a circular roof. The cylinder, sharing the same circular cross-section as the cone's base, produces a seamless joint.
Refactoring: organizing code into functions
When all the code lives in a single flat block, scaling the application by adding more objects quickly becomes chaotic. The solution is to encapsulate each element in its own function and create an init() function that initializes the base elements (scene, camera, renderer) and calls all the others passing the scene as a parameter:
function init() {
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight)
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
// llamadas a cada elemento del jardín
house(scene)
bar(scene)
tree(scene)
floor(scene)
camera.position.z = 20
camera.position.y = 20
camera.lookAt(scene.position)
renderer.render(scene, camera)
}
init()This pattern has clear advantages:
- No global variables: the scene is created inside
init()and passed as an argument to each function, avoiding access from the global scope. - Modularity: to add a new element you just create a
function myElement(scene)function and call it frominit(). - Readability: each function has a single responsibility and its name describes exactly what it builds.
Adjusting the camera with lookAt
With several objects scattered across the scene it is important to point the camera toward the center of the garden. Instead of manually calculating rotation angles, we use lookAt() pointing to the scene's position (the origin 0, 0, 0):
camera.position.z = 20
camera.position.y = 20
camera.lookAt(scene.position)Positioning the camera at y = 20 and z = 20 gives a diagonal isometric angle that shows both the ground and the objects well. lookAt(scene.position) takes care of rotating the camera automatically so it looks toward the origin, no matter where it is located.
Fine-tuning positions
Once all objects are assembled it is common for some to float or intersect with the ground. Some adjustments made in this final phase:
- The ground drops to
y = -0.5instead of-1to eliminate the dead space left between the floor and the base of the objects. - Floating objects are shifted on Y until their base touches the plane.
- The fence bars are readjusted on Z to sit right on the edge of the plane without sticking out or falling short.
To verify positioning it is helpful to temporarily change the camera's position and observe the scene from different angles: from above with positive y, from below with negative y, from the side adjusting only z. This helps spot objects that stick out or leave unwanted gaps.
The complete source code
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Proyecto Jardín</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="../js/three.js"></script>
<script>
function init() {
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight)
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
house(scene)
bar(scene)
tree(scene)
floor(scene)
camera.position.z = 20
camera.position.y = 20
camera.lookAt(scene.position)
renderer.render(scene, camera)
}
function house(scene) {
// Casa: base cilindrica
const houseBaseGeometry = new THREE.CylinderGeometry(2, 2, 3)
const houseBaseMaterial = new THREE.MeshBasicMaterial({ color: 0xFFEECC })
const houseBase = new THREE.Mesh(houseBaseGeometry, houseBaseMaterial)
houseBase.position.y = 1
houseBase.position.x = 5
scene.add(houseBase)
// Techo en forma de cono
const houseRoofGeometry = new THREE.ConeGeometry(2, 3, 15)
const houseRoofMaterial = new THREE.MeshBasicMaterial({ color: 0x776600 })
const houseRoof = new THREE.Mesh(houseRoofGeometry, houseRoofMaterial)
houseRoof.position.y = 4
houseRoof.position.x = 5
scene.add(houseRoof)
}
function bar(scene) {
const barMaterial = new THREE.MeshBasicMaterial({ color: 0x994422 })
const geometryBarRightLeft = new THREE.BoxGeometry(1, 1, 11)
const barRight = new THREE.Mesh(geometryBarRightLeft, barMaterial)
barRight.position.x = 10
scene.add(barRight)
const barLeft = new THREE.Mesh(geometryBarRightLeft, barMaterial)
barLeft.position.x = -10
scene.add(barLeft)
const geometryBarUpBottom = new THREE.BoxGeometry(19, 1, 1)
const barUp = new THREE.Mesh(geometryBarUpBottom, barMaterial)
barUp.position.z = 5
scene.add(barUp)
const barBottom = new THREE.Mesh(geometryBarUpBottom, barMaterial)
barBottom.position.z = -5
scene.add(barBottom)
}
function floor(scene) {
const planeGeometry = new THREE.PlaneGeometry(20, 10)
const planeMaterial = new THREE.MeshBasicMaterial({
color: 0x779922,
wireframe: false
})
var plane = new THREE.Mesh(planeGeometry, planeMaterial)
plane.rotation.x = -0.5 * Math.PI
plane.position.y = -0.5
scene.add(plane)
}
function tree(scene) {
// Tronco
const trunkGeometry = new THREE.BoxGeometry(1, 8, 1)
const trunkMaterial = new THREE.MeshBasicMaterial({ color: 0x110000 })
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial)
trunk.position.y = 3
trunk.position.x = -3
scene.add(trunk)
// Forraje / hojas
const fodderGeometry = new THREE.SphereGeometry(4, 5, 6)
const fodderMaterial = new THREE.MeshBasicMaterial({ color: 0x00AA00 })
const fodder = new THREE.Mesh(fodderGeometry, fodderMaterial)
fodder.position.y = 9
fodder.position.x = -3
scene.add(fodder)
}
init()
</script>
</body>
</html>Chapter summary
In this chapter we applied all the fundamentals from the previous chapter in a realistic and complete project:
- We built the floor with a solid
PlaneGeometry(no wireframe) and rotated it using radians. - We learned CylinderGeometry: top radius, bottom radius, height, and segments.
- We learned ConeGeometry: base radius, height, and segments.
- We saw how to stack primitives to create complex objects (tree = trunk + sphere; house = cylinder + cone).
- We practiced material reuse across multiple meshes.
- We refactored the code using functions with
sceneas a parameter, following theinit()pattern. - We adjusted the camera with
lookAt(scene.position)to frame the entire scene.
This pattern of separate functions per element is the foundation of the workflow we will use in the more complex projects of upcoming chapters.
Source: