用three.js 写一段代码,实现点击按钮1弹出对话框输入一个点的坐标,点击按钮2弹出对话框输入第二个点坐标,然后点击按钮3在两点之间绘制一个管状线条. 按钮1在网页顶端的最左侧,按钮2在网页顶端的最右侧,按钮3在网页顶部居中。
时间: 2024-09-10 10:12:42 浏览: 74
在Three.js中,实现这个功能需要结合HTML、JavaScript以及THREE库。以下是一个简单的示例代码,假设你已经创建了一个HTML页面,并引入了three.js库:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Three.js Line Renderer</title>
<style>
body { margin: 0; }
canvas { display: block; }
</style>
</head>
<body>
<div id="topBar">
<button id="pointA">点A</button>
<button id="pointB">点B</button>
<button id="drawLine">画线</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.140.0/build/three.min.js"></script>
<script src="main.js"></script>
</body>
</html>
```
然后在`main.js`文件中编写JavaScript部分:
```javascript
// 创建场景、相机和渲染器
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 pointAButton = document.getElementById('pointA');
const pointBButton = document.getElementById('pointB');
const drawLineButton = document.getElementById('drawLine');
pointAButton.addEventListener('click', () => {
prompt('请输入点A的坐标(x, y, z):', '').then(point => createPoint(scene, 'A', point));
});
pointBButton.addEventListener('click', () => {
prompt('请输入点B的坐标(x, y, z):', '').then(point => createPoint(scene, 'B', point));
});
drawLineButton.addEventListener('click', () => {
if (scene.children.length >= 2) { // 如果已经有两个点
const lineGeometry = new THREE.BufferGeometry().setFromPoints([scene.getObjectByName('A').position, scene.getObjectByName('B').position]);
const tubeMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); // 管状材质
const tubeMesh = new THREE.LineSegments(lineGeometry, tubeMaterial);
scene.add(tubeMesh);
console.log("Line drawn between A and B");
} else {
alert('请先输入两个点的坐标');
}
});
function createPoint(scene, name, pointStr) {
const [x, y, z] = JSON.parse(pointStr).split(',').map(Number);
const sphereGeometry = new THREE.SphereGeometry(0.05, 32, 32);
const sphereMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.set(x, y, z);
scene.add(sphere);
scene.add(new THREE.AxisHelper(1)); // 添加坐标轴辅助查看位置
scene.objects = scene.children;
}
// 渲染
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
```
这个示例中,我们首先创建了三个按钮,分别对应输入点的坐标和画线操作。当用户点击相应按钮时,会弹出提示框获取输入并创建球体表示点的位置。当画线按钮点击时,检查是否有两个点存在,如果有则计算线段并添加到场景中。
注意这只是一个基础的示例,实际应用中可能需要对用户输入进行更严格的验证和错误处理。同时,Three.js还提供了许多其他交互式功能,如Raycaster用于鼠标点击检测等。
阅读全文