上述HTML文档是一个使用Three.js库创建的简单WebGL应用程序,主要用于展示具有不同透明度和缩放比例的圆环列。以下是代码的详细解释:
总之,这段代码展示了一个基本的Three.js应用,通过动态改变对象的属性和使用简单的光照来创建一个有趣的视觉效果。
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - particles - columns</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
margin: 0;
}
canvas {
display: block;
}
</style>
</head>
<body>
<script type="module">
import * as THREE from 'three';
import { Scene, PerspectiveCamera, WebGLRenderer, AmbientLight, Color, SpotLight } from "three";
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// 初始化场景、相机和渲染器
const scene = new Scene();
const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const meshes = [];
for (let i = 0; i < 4; i++) {
const geometry = new THREE.RingGeometry(0.9, 1, );
const opacity = 1 - i / 4; // 计算透明度
const scale = (16 * i) / 4 + 1; // 计算缩放比例
const material = new THREE.MeshBasicMaterial({
color: 0x3184ae,
transparent: true,
opacity: opacity, // 使用计算的透明度
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
mesh.scale.set(scale, scale, 1);
meshes.push(mesh);
}
// 遍历 meshes 数组,并将每个 mesh 添加到场景中
meshes.forEach(mesh => {
scene.add(mesh);
});
//
// 添加环境光和聚光灯
const ambientLight = new AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const spotLight = new SpotLight(0xffffff, 1);
spotLight.position.set(10, 10, 10);
scene.add(spotLight);
/
// 设置相机位置
camera.position.z = 50;
// 添加OrbitControls以便交互
const controls = new OrbitControls(camera, renderer.domElement);
const render = () => {
meshes.forEach((mesh, index) => {
const meterial = mesh.material;
if (meterial.opacity <= 0) {
meterial.opacity = 1;
mesh.scale.set(1, 1, 1);
} else { meterial.opacity -= 0.002; mesh.scale.set(mesh.scale.x + 0.038, mesh.scale.y + 0.038, 1); }
});
};
// 创建动画循环
const animate = function () {
requestAnimationFrame(animate);
render();
controls.update(); // 更新OrbitControls
renderer.render(scene, camera);
};
// 处理窗口大小调整
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// 开始动画循环
animate();
</script>
</body>
</html>