20个基于Three.js的代码示例
以下是20个基于Three.js的代码示例,涵盖了创建3D场景、添加几何体、添加材质和纹理、添加灯光以及动画等常见的3D场景元素。
- 创建一个简单的3D立方体:
// 创建场景
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);
// 创建立方体
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({color: 0x00ff00});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
const animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
- 创建一个带有纹理的3D球体:
// 加载纹理
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('path/to/texture.jpg');
// 创建材质
const material = new THREE.MeshBasicMaterial({map: texture});
const sphereGeometry = new THREE.SphereGeometry(1, 20, 20);
const sphere = new THREE.Mesh(sphereGeometry, material);
scene.add(sphere);
- 添加环境光和点光源:
// 环境光
scene.add(new THREE.AmbientLight(0x404040));
// 点光源
const pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(10, 0, 25);
scene.add(pointLight);
- 使用OBJLoader加载复杂的3D模型:
const objLoader = new THREE.OBJLoader();
objLoader.load('path/to/model.obj', 'path/to/model.mtl', function (object) {
scene.add(object);
});
- 添加鼠标旋转控制:
new THREE.OrbitControls(camera);
- 添加简单的动画:
function animate() {
requestAnimationFrame(animate);
// 旋转立方体
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
- 使用GUI库添加可配置参数:
// 创建GUI
const gui = new dat.GUI();
gui.add(scene, 'fog').name('Fog');
gui.addColor(scene, 'background').name('Background Color');
- 使用Post Processing添加后处理效果:
const renderPass = new THREE.RenderPass(scene, camera);
const effectPass = new THREE.ShaderPass(THREE.DigitalGlitch);
effectPass.uniforms['duration'].value = 2.0;
effectPass.uniforms['strength'].value = 1.5;
const composer = new THREE.EffectComposer(renderer);
composer.addPass(renderPass);
composer.addPass(effectPass);
评论已关闭