← Volver

Three.js crear proyecto

Publicado el 4 de mayo de 2025

Para crear el proyecto de Three.js vamos a utilizar la siguiente plantilla de código:

Clase ThreeManager.js

import * as THREE from "three";

export class ThreeManager {
    constructor() {
        this.canvas = null;
        this.scene = null;
        this.camera = null;
        this.renderer = null;

        this.fov = null;
        this.aspetRatio = null;
        this.near = null;
        this.far = null;

        this.positionX = null;
        this.positionY = null;
        this.positionZ = null;

        this.controls = null;
    };

    init() {
        this.createScene();
        this.createCamera();
        this.createRenderer();
        this.createLights();

    }

    setCanvas(canvasId) {
        this.canvas = document.querySelector(canvasId);
    }

    createScene() {
        this.scene = new THREE.Scene();
    }

    getScene() {
        return this.scene;
    }

    addToScene(model) {
        this.scene.add(model)
    }

    setCamera(fov, aspectRatio, near, far, positionX, positionY, positionZ) {
        this.fov = fov;
        this.aspetRatio = aspectRatio;
        this.near = near;
        this.far = far;
        this.positionX = positionX;
        this.positionY = positionY;
        this.positionZ = positionZ;
    }

    createCamera() {
        this.camera = new THREE.PerspectiveCamera(this.fov, this.aspetRatio, this.near, this.far);
        this.camera.position.set(this.positionX, this.positionY, this.positionZ);
        this.camera.lookAt(new THREE.Vector3(0, 0, 0));
    }

    cameraLookAt(model) {
        this.camera.lookAt(model.position);
    }

    getCamera() {
        return this.camera;
    }

    createRenderer() {
        this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas });
        this.renderer.setSize(window.innerWidth, window.innerHeight);
    }

    getRenderer() {
        return this.renderer;
    }

    createLights() {
        const ambientLight = new THREE.AmbientLight(0xffffff, 1);
        this.scene.add(ambientLight);

        const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
        directionalLight.position.set(3, 10, 5);
        this.scene.add(directionalLight);
    }




}

Ahora llamamos a los métodos desde el main.js

import { ThreeManager } from "./ThreeManager";

const threeManager = new ThreeManager();
threeManager.setCanvas("canvas");
threeManager.setCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000, 0, 2, 10);
threeManager.init();

const animate = () => {
  threeManager.getRenderer().render(threeManager.getScene(), threeManager.getCamera());

}

threeManager.getRenderer().setAnimationLoop(animate);