Three.js Sahne Oluşturma ve İlk Örnek (Küp Döndürme)

Node.js yüklü ise aşağıdaki komutları çalıştırın ve Three.js ve Vite build aracını projenize ekleyin.

# three.js
npm install --save three

# vite
npm install --save-dev vite

Projenizi npx vite komutu ile boş olarak build edin ve http://localhost:5173/ adresinde çalıştığından emin olun.

npx vite

index.html dosyanızı aşağıdaki gibi oluşturun.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>My first three.js app</title>
    <style>
        body { margin: 0; }
    </style>
</head>
<body>
<script type="module" src="/main.js"></script>
</body>
</html>

main.js dosyanızı aşağıdaki gibi oluşturun ve açıklama satırlarını takip edin.

  • Sahne ve kameranın oluşturulması
  • WebGL renderer’ın oluşturulması ve tarayıcı penceresine eklenmesi
  • Küp geometrisinin oluşturulması, kaplanması ve sahneye eklenmesi
import * as THREE from 'three';
import {func} from "three/addons/nodes/code/FunctionNode";


const scene = new THREE.Scene();

/*
    Perspective Camera Settings

    fov: görüş alanı
    aspect ratio: en boy oranı
    near and far: çok yakındaki ve çok uzaktaki nesnelerin kesilmesi
*/
const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
);

// kamera uzaklık ayarı. küpün daha yakın ya da uzaktan gösterir.
camera.position.z = 2;


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


// Küp oluşturma işlemleri
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({color: 0xff00ff});
const cube = new THREE.Mesh(geometry, material);


// Küpün sahneye eklenmesi
scene.add(cube);


// Küpe hareket vermek için her frame'de animasyon oluşturuyoruz.
function animate(){
    requestAnimationFrame(animate);

    cube.rotation.x += 0.001;
    cube.rotation.y += 0.001;

    renderer.render( scene, camera );
}


animate();