Getting Started with Three.js: A Beginner’s Guide with Sample Code

  • 2024/11/14
  • Getting Started with Three.js: A Beginner’s Guide with Sample Code はコメントを受け付けていません

Introduction to Three.js

Three.js is a powerful, open-source JavaScript library that makes creating 3D graphics on the web simpler and more accessible. Developed as a high-level layer on top of WebGL, Three.js allows you to create and render complex 3D graphics without delving deep into the technical complexities of WebGL. With Three.js, you can create interactive 3D models, animations, and environments right inside the browser, making it ideal for games, visualizations, and any application that needs immersive graphics.

In this blog, we’ll cover:

  1. Basics of Three.js
  2. Setting up a simple Three.js scene
  3. Sample projects showcasing Three.js capabilities

Basics of Three.js

Core Concepts

Three.js primarily operates on three concepts: Scenes, Cameras, and Renderers.

  • Scene: This is where all the objects, lights, and cameras are placed.
  • Camera: Defines the perspective from which the scene is viewed. Three.js offers different types of cameras, with the PerspectiveCamera being the most commonly used for 3D scenes.
  • Renderer: This is responsible for displaying the 3D scene to the screen.

In addition to these core elements, Three.js provides a wide array of built-in objects (like spheres, cubes, and planes) and materials (like textures, colors, and lights) to give objects realistic properties.

Setting Up Your First Scene in Three.js

To start with Three.js, include it via a CDN link or install it via npm:

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>

Or, install with npm:

npm install three

Then, follow these steps to create a simple scene.

Step-by-Step Code Example: Basic Scene Setup

Create the Scene, Camera, and Renderer

// Step 1: Set up scene, camera, and renderer
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);

Add a Cube

// Step 2: Create a cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

Set Camera Position and Animate the Scene

// Step 3: Position the camera and create an animation loop
camera.position.z = 5;

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

This code creates a rotating green cube that renders in your browser.

Fascinating Sample Codes with Three.js

Code for a Glowing Wireframe Sphere

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js Glowing Wireframe Sphere</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<script>
// Setup scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000); // Black background for contrast
document.body.appendChild(renderer.domElement);


// Light to give ambient effect to the scene
const ambientLight = new THREE.AmbientLight(0x404040, 2);
scene.add(ambientLight);


// Step 1: Create a Wireframe Sphere with a Custom Shader Material for Glow
const sphereGeometry = new THREE.SphereGeometry(1, 32, 32);


// Custom Shader Material
const sphereMaterial = new THREE.ShaderMaterial({
uniforms: {
color: { value: new THREE.Color(0x00ffff) }, // Glow color
time: { value: 0.0 }
},
vertexShader: `
uniform float time;
void main() {
// Increase the position for animation
vec3 pos = position + normal * 0.1 * sin(time + position.x * 5.0);
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`,
fragmentShader: `
uniform vec3 color;
void main() {
gl_FragColor = vec4(color, 1.0);
}
`,
wireframe: true,
});


const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
scene.add(sphere);


// Position the camera
camera.position.z = 3;


// Animate the sphere with a pulsing effect and rotation
function animate() {
requestAnimationFrame(animate);


// Update shader time for pulsing effect
sphereMaterial.uniforms.time.value += 0.02;


// Rotate sphere for dynamic effect
sphere.rotation.y += 0.01;


// Render the scene
renderer.render(scene, camera);
}


animate();


// Resize handling
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
</script>
</body>
</html>

This is the result we achieved with the code above.


As you can see, Three.js opens up endless possibilities for bringing your ideas to life in 3D. With its extensive features and flexibility, it’s an incredible tool for creative projects. Whether you’re a beginner or an experienced developer, Three.js has something for everyone—so dive in and see what you can create!

関連記事

カテゴリー:

未分類

情シス求人

  1. チームメンバーで作字やってみた#1

ページ上部へ戻る