Three.js 必背核心方法

4 阅读1分钟

一、场景(容器,放所有东西)

const scene = new THREE.Scene();

作用:3D 世界的容器,所有物体、灯光、相机都要放进去。

二、相机(观察者视角,2 种最常用)

1. 透视相机(人眼视角,最常用)

const camera = new THREE.PerspectiveCamera(
    fov, // 视野角度(推荐 50~75)
    aspect, // 宽高比(画布宽/高)
    near, // 近裁剪面(≥0.1,太近会穿模)
    far // 远裁剪面(能看多远)
);

常用设置

camera.position.set(x, y, z); // 相机位置
camera.lookAt(x, y, z); // 相机看向哪

2. 正交相机(2D视角,无近大远小)

const camera = new THREE.OrthographicCamera( left, right, top, bottom, near, far );

三、渲染器(把画面画到屏幕)

const renderer = new THREE.WebGLRenderer({
    antialias: true, // 抗锯齿(必开)
    alpha: true // 开启透明通道
});
renderer.setSize(width, height); // 设置画布大小
renderer.render(scene, camera); // 渲染画面(核心方法)

四、物体(网格 = 形状 + 材质)

1. 创建几何体(形状)

const geometry = new THREE.BoxGeometry(宽, 高, 深); 

2. 创建材质(外观/颜色)

// 基础材质(不受光影响)
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });

// 标准材质(受光影响,真实感) 
const material = new THREE.MeshStandardMaterial({ color: 0xff0000 }); 

3. 创建网格(最终物体)

const mesh = new THREE.Mesh(geometry, material); 
scene.add(mesh); // 加入场景 

4. 物体常用属性

mesh.position.set(x,y,z); // 位置 
mesh.rotation.set(x,y,z); // 旋转(弧度) 
mesh.scale.set(x,y,z); // 缩放 

五、光源(让物体有明暗)

1. 平行光(太阳,最常用)

const light = new THREE.DirectionalLight(颜色, 强度); 
light.position.set(x,y,z); 
scene.add(light); 

2. 环境光(全局柔光,防止全黑)

const ambient = new THREE.AmbientLight(颜色, 强度); 
scene.add(ambient); 

六、动画循环(动起来)

function animate() { 
    requestAnimationFrame(animate); // 在这里写动画:旋转/移动物体 
    mesh.rotation.y += 0.01; 
    renderer.render(scene, camera); 
} 
animate(); 

七、辅助工具(调试神器)

1. 坐标轴辅助

const axesHelper = new THREE.AxesHelper(长度); 
scene.add(axesHelper); 

2. 相机辅助

const cameraHelper = new THREE.CameraHelper(camera); 
scene.add(cameraHelper);