以下是使用three.js绘制皮亚诺曲线的示例代码:
// 创建场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建皮亚诺曲线
const curve = new THREE.Curve();
curve.getPoint = function (t) {
const x = t * 2 - 1;
const y = t * t * t;
return new THREE.Vector3(x, y, 0);
};
// 创建曲线路径
const path = new THREE.Path();
path.add(new THREE.LineCurve(new THREE.Vector3(-1, 0, 0), new THREE.Vector3(1, 0, 0)));
for (let i = 0; i < 10; i++) {
const points = path.getPoints(100);
const newPath = new THREE.Path();
for (let j = 0; j < points.length; j++) {
const point = points[j];
const tangent = path.getTangentAt(point).normalize();
const normal = new THREE.Vector3().crossVectors(tangent, new THREE.Vector3(0, 1, 0)).normalize();
const binormal = new THREE.Vector3().crossVectors(tangent, normal).normalize();
const position = point.clone().add(normal.multiplyScalar(curve.getPoint(i / 10).y));
newPath.add(new THREE.LineCurve(position, position.clone().add(binormal)));
}
path = newPath;
}
// 创建曲线几何体和材质,并添加到场景中
const geometry = new THREE.Geometry();
geometry.vertices = path.getPoints(1000);
const material = new THREE.LineBasicMaterial({ color: 0xff0000 });
const line = new THREE.Line(geometry, material);
scene.add(line);
// 设置相机位置和渲染循环
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
```
这段代码使用了three.js库来创建一个场景、相机和渲染器,然后通过定义一个`getPoint`函数来生成皮亚诺曲线上的点。接着,使用这些点来创建一条曲线路径,并通过迭代的方式将路径细分为更小的线段。最后,将这些线段作为几何体添加到场景中,并设置相机位置和渲染循环来显示结果。