基于Three.js 绘制3维折线图,并带有坐标系, 请给出完整代码
时间: 2024-03-27 10:35:42 浏览: 153
js绘制折线图
4星 · 用户满意度95%
以下是一个基于Three.js绘制3维折线图并带有坐标系的完整代码示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Three.js 3D Line Chart with Axes</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
const data = [
{ x: 0, y: 0, z: 0 },
{ x: 1, y: 1, z: 0 },
{ x: 2, y: 2, z: 1 },
{ x: 3, y: 1, z: 1 },
{ x: 4, y: 3, z: 2 },
{ x: 5, y: 2, z: 2 },
{ x: 6, y: 4, z: 3 },
{ x: 7, y: 3, z: 3 },
{ x: 8, y: 5, z: 4 },
{ x: 9, y: 4, z: 4 }
];
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(10, 10, 10);
camera.lookAt(scene.position);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add axes to the scene
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// Add grid to the scene
const size = 10;
const divisions = 10;
const gridHelper = new THREE.GridHelper(size, divisions);
scene.add(gridHelper);
// Create line chart
const material = new THREE.LineBasicMaterial({ color: 0x0000ff });
const geometry = new THREE.Geometry();
for (let i = 0; i < data.length; i++) {
geometry.vertices.push(new THREE.Vector3(data[i].x, data[i].y, data[i].z));
}
const line = new THREE.Line(geometry, material);
scene.add(line);
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```
这个例子中,我们创建了一个包含10个点的3维数据集,然后使用Three.js创建了一个3维折线图。我们使用了`THREE.Line`对象,并将其添加到了场景中。在动画循环中,我们不断地渲染场景。此外,我们还添加了坐标系和网格,以帮助我们更好地理解场景中的元素位置。
阅读全文