simple 3D scene

simple 3D scene

Importing Three.js:

Creating the Scene, Camera, and Renderer:

  • const scene = new THREE.Scene(); creates a scene to hold the 3D objects.

  • const camera = new THREE.PerspectiveCamera(...); creates a perspective camera, defining how the scene is viewed.

  • const renderer = new THREE.WebGLRenderer(); creates a renderer to draw the 3D scene onto a canvas element.

Setting Renderer Size and Pixel Ratio:

  • renderer.setSize(window.innerWidth, window.innerHeight); sets the renderer's size to match the browser window.

  • renderer.setPixelRatio(devicePixelRatio); ensures high-quality rendering on high-resolution displays.

  • document.body.appendChild(renderer.domElement); adds the renderer's canvas to the HTML document, making it visible.

    Creating a Green Box:

  • const boxGeometry = new THREE.BoxGeometry(1, 1, 1); creates a cube-shaped geometry with dimensions of 1x1x1.

  • const material = new THREE.MeshBasicMaterial({ color: 0x00FF00 }); creates a material with a green color.

  • const mesh = new THREE.Mesh(boxGeometry, material); combines the geometry and material to create a green box mesh.

  • scene.add(mesh); adds the box to the scene.

Positioning the Camera:

  • camera.position.z = 6; moves the camera 6 units away from the origin, providing a better view of the box.

Animation Loop:

  • The animate function creates an animation loop using requestAnimationFrame:

    • requestAnimationFrame(animate); schedules the next animation frame for smooth rendering.

    • renderer.render(scene, camera); renders the scene from the camera's perspective.

    • mesh.rotation.x += 0.01; and mesh.rotation.y += 0.01; rotate the box slightly around its X and Y axes in each frame, creating a continuous spinning motion.

Starting the Animation:

  • animate(); initially calls the animate function to start the animation loop.
import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';
const scene = new THREE.Scene();
const camera= new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000);
const renderer= new THREE.WebGLRenderer();
console.log(scene);
console.log(camera);
console.log(renderer);
// Create a black box
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(devicePixelRatio);
document.body.appendChild(renderer.domElement);

const boxGeometry = new THREE.BoxGeometry(1,1,1)
const material = new THREE.MeshBasicMaterial({color: 0x00FF00})
console.log(boxGeometry)
console.log(material)
const mesh =new THREE.Mesh(boxGeometry,material)
console.log(mesh)
scene.add(mesh)
 camera.position.z =6
function

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

Overall, this code creates a simple 3D scene with a green box rotating smoothly in space, demonstrating the basic setup and animation process in Three.js.