生成一个可直接浏览器运行的threejs的简单demo,要求使用BufferGeometry 根据8个顶点坐标创建一个8边形面,加入鼠标左键操作视角转动
时间: 2024-10-12 10:12:13 浏览: 20
当然可以,这是一个简单的Three.js示例,它会在浏览器中运行,并使用BufferGeometry创建一个8边形。当你按下鼠标左键并拖动时,场景会随着鼠标的移动而旋转:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Eight-Sided Polygon with BufferGeometry</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
<script src="https://threejs.org/build/three.min.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// 创建一个WebGL渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 场景和相机设置
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 5, 10); // 设置初始视点
// 加载几何体
const geometry = new THREE.BufferGeometry();
let positions = [];
for (let i = 0; i <= 8; i++) {
positions.push(Math.cos(i * Math.PI / 4), Math.sin(i * Math.PI / 4), 0);
}
geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
// 创建Mesh
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// 鼠标交互
function onDocumentMouseDown(event) {
event.preventDefault(); // 阻止默认的右键菜单显示
renderer.domElement.addEventListener('mousemove', onMouseMove, false);
renderer.domElement.addEventListener('mouseup', onMouseUp, false);
}
function onDocumentMouseUp() {
renderer.domElement.removeEventListener('mousemove', onMouseMove, false);
renderer.domElement.removeEventListener('mouseup', onMouseUp, false);
}
function onMouseMove(event) {
camera.rotation.y += (event.clientX - renderer.domElement.getBoundingClientRect().left) * 0.01;
}
function onMouseUp() {
onDocumentMouseUp();
}
// 添加事件监听
document.addEventListener('mousedown', onDocumentMouseDown, false);
// 渲染循环
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```
这个示例展示了如何创建一个8边形,使用BufferGeometry并添加鼠标交互以改变视角。在浏览器中打开这个HTML文件,即可看到效果。
阅读全文