Interview

10 Three.js Interview Questions and Answers

Prepare for your next interview with this guide on Three.js, featuring common questions and answers to enhance your 3D web development skills.

Three.js is a powerful JavaScript library that simplifies the creation of 3D graphics in web browsers. Leveraging WebGL, Three.js allows developers to build complex 3D environments and animations with relative ease, making it a popular choice for interactive web applications, games, and data visualizations. Its extensive documentation and active community support make it accessible for both beginners and experienced developers.

This article provides a curated selection of interview questions designed to test your understanding and proficiency with Three.js. By working through these questions, you will gain deeper insights into the library’s capabilities and be better prepared to demonstrate your expertise in a technical interview setting.

Three.js Interview Questions and Answers

1. Write the code to set up a basic scene with a cube and a perspective camera.

To set up a basic scene with a cube and a perspective camera in Three.js, follow these steps:

1. Create a scene, camera, and renderer.
2. Create a cube geometry and material.
3. Add the cube to the scene.
4. Render the scene.

Example:

import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

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: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);

scene.add(cube);

function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
}
animate();

2. How do you create a sphere geometry with a Phong material? Provide the code.

To create a sphere geometry with a Phong material in Three.js:

1. Initialize the scene, camera, and renderer.
2. Create the sphere geometry.
3. Apply the Phong material.
4. Add the sphere to the scene.
5. Render the scene.

Example:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, 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.SphereGeometry(5, 32, 32);
const material = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);

const light = new THREE.PointLight(0xffffff);
light.position.set(10, 10, 10);
scene.add(light);

camera.position.z = 20;
renderer.render(scene, camera);

3. Describe the process of loading an external GLTF model into a scene. Include a code example.

To load an external GLTF model into a Three.js scene:

1. Set up the scene, camera, and renderer.
2. Use the GLTFLoader to load the model.
3. Add the model to the scene.
4. Render the scene.

Example:

import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const loader = new GLTFLoader();
loader.load('path/to/model.gltf', function (gltf) {
    scene.add(gltf.scene);
    renderer.render(scene, camera);
}, undefined, function (error) {
    console.error(error);
});

camera.position.z = 5;

function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}
animate();

4. What are shaders, and how would you use a custom vertex and fragment shader? Provide a simple example.

Shaders are small programs that run on the GPU to control rendering. In Three.js, shaders are written in GLSL and manipulate vertices and pixels. There are vertex shaders for vertex positions and fragment shaders for pixel colors.

To use custom shaders, create a ShaderMaterial with your vertex and fragment shader code. Example:

const vertexShader = `
  void main() {
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  }
`;

const fragmentShader = `
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // Red color
  }
`;

const material = new THREE.ShaderMaterial({
  vertexShader: vertexShader,
  fragmentShader: fragmentShader
});

const geometry = new THREE.BoxGeometry();
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

5. Write the code to implement raycasting for object selection in a scene.

Raycasting in Three.js detects intersections of a ray with objects in a scene, often for object selection.

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, 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: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

function onMouseClick(event) {
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    const intersects = raycaster.intersectObjects(scene.children);

    if (intersects.length > 0) {
        console.log('Object selected:', intersects[0].object);
    }
}

window.addEventListener('click', onMouseClick, false);

function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}
animate();

6. Describe how to integrate Cannon.js for physics simulation. Include a basic example.

To integrate Cannon.js for physics simulation in a Three.js project:

1. Set up a Three.js scene.
2. Initialize the Cannon.js world.
3. Create objects in both Three.js and Cannon.js.
4. Synchronize the physics simulation with the rendering loop.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Three.js and Cannon.js Integration</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.min.js"></script>
</head>
<body>
    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        var world = new CANNON.World();
        world.gravity.set(0, -9.82, 0);

        var groundBody = new CANNON.Body({
            mass: 0,
            shape: new CANNON.Plane()
        });
        groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
        world.addBody(groundBody);

        var groundGeometry = new THREE.PlaneGeometry(10, 10);
        var groundMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        var groundMesh = new THREE.Mesh(groundGeometry, groundMaterial);
        groundMesh.rotation.x = -Math.PI / 2;
        scene.add(groundMesh);

        var sphereBody = new CANNON.Body({
            mass: 1,
            shape: new CANNON.Sphere(1)
        });
        sphereBody.position.set(0, 5, 0);
        world.addBody(sphereBody);

        var sphereGeometry = new THREE.SphereGeometry(1, 32, 32);
        var sphereMaterial = new THREE.MeshBasicMaterial({ color: 0x0000ff });
        var sphereMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
        scene.add(sphereMesh);

        camera.position.z = 10;

        function animate() {
            requestAnimationFrame(animate);

            world.step(1 / 60);

            sphereMesh.position.copy(sphereBody.position);
            sphereMesh.quaternion.copy(sphereBody.quaternion);

            renderer.render(scene, camera);
        }

        animate();
    </script>
</body>
</html>

7. Write the code to create a custom geometry (e.g., a pyramid).

To create a custom geometry in Three.js, use the THREE.BufferGeometry class. Example of a pyramid:

const scene = new THREE.Scene();

const vertices = new Float32Array([
    0, 1, 0,  // Top vertex
    -1, -1, 1,  // Front-left vertex
    1, -1, 1,  // Front-right vertex
    1, -1, -1,  // Back-right vertex
    -1, -1, -1  // Back-left vertex
]);

const indices = [
    0, 1, 2,  // Front face
    0, 2, 3,  // Right face
    0, 3, 4,  // Back face
    0, 4, 1,  // Left face
    1, 2, 3,  // Bottom face part 1
    1, 3, 4   // Bottom face part 2
];

const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.setIndex(indices);

const material = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });

const pyramid = new THREE.Mesh(geometry, material);

scene.add(pyramid);

8. Explain the difference between MeshBasicMaterial and MeshStandardMaterial. When would you use each?

MeshBasicMaterial:

  • MeshBasicMaterial is unaffected by lights. It displays the color or texture of the object without shading or lighting effects.
  • Useful for objects that need a constant appearance, like background elements or wireframes.

MeshStandardMaterial:

  • MeshStandardMaterial is a physically-based rendering (PBR) material that interacts with lights, supporting reflections, refractions, and realistic shading.
  • Ideal for objects that need to appear realistic and respond to the lighting environment.

9. How do you handle textures? Provide an example of loading and applying a texture to a mesh.

In Three.js, textures are images applied to 3D objects to add detail and realism. Handling textures involves loading the image and applying it to a mesh material.

Example:

import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('path/to/texture.jpg');

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ map: texture });

const cube = new THREE.Mesh(geometry, material);

scene.add(cube);

function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
}
animate();

10. Describe how to use the AnimationMixer for animating models. Include a code example.

The AnimationMixer in Three.js manages animations on objects, allowing for smooth transitions and blending. It works with AnimationClips, sequences of keyframe tracks defining the animation.

To use the AnimationMixer:

  • Create an instance of AnimationMixer and pass the object to be animated.
  • Load or create an AnimationClip.
  • Use the mixer to play the clip.

Example:

const model = loadedModel.scene;
const mixer = new THREE.AnimationMixer(model);

const clip = loadedModel.animations[0];
const action = mixer.clipAction(clip);
action.play();

const clock = new THREE.Clock();

function animate() {
    requestAnimationFrame(animate);
    const delta = clock.getDelta();
    mixer.update(delta);
    renderer.render(scene, camera);
}

animate();
Previous

10 Media Queries Interview Questions and Answers

Back to Interview
Next

10 Mobile Device Management Interview Questions and Answers