three.js 镜面
·
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Three.js镜面反射</title>
<style>body { margin: 0; }</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/objects/Reflector.js"></script>
<script>
// 初始化场景
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 添加光源
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 10, 7);
scene.add(light);
scene.add(new THREE.AmbientLight(0x404040));
// 创建镜面
const mirror = new THREE.Reflector(
new THREE.PlaneGeometry(10, 10),
{
clipBias: 0.003,
textureWidth: window.innerWidth,
textureHeight: window.innerHeight,
color: 0x888888
}
);
mirror.rotateX(-Math.PI/2);
mirror.position.y = -2;
scene.add(mirror);
// 添加反射物体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({
color: 0x00aaff,
roughness: 0.1,
metalness: 0.9
});
const cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 2, -3);
scene.add(cube);
// 相机位置
camera.position.set(0, 5, 10);
camera.lookAt(0, 0, 0);
// 动画循环
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
// 响应窗口大小变化
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
更多推荐
所有评论(0)