项目中,线段数据后端传过来上万个,如何我们一条一条线段往里面加,导致页面性能下降,这个时候,我们可以将所有线段合并成一个
老代码,也能实现功能
const lineGroup = new THREE.Group();
this.bezierPathList.forEach((item) => {
const [p1, p2, p3, p4] = item.coordinate;
// 初始化数据,绘制曲线轨迹
const curve = new THREE.CubicBezierCurve3(
new THREE.Vector3(p1.x / 1000, 0.1, -p1.z / 1000), // z轴取反
new THREE.Vector3(p2.x / 1000, 0.1, -p2.z / 1000),
new THREE.Vector3(p3.x / 1000, 0.1, -p3.z / 1000),
new THREE.Vector3(p4.x / 1000, 0.1, -p4.z / 1000)
);
const points = curve.getPoints(50);
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({ color: 0xffffff });
const curveObject = new THREE.Line(geometry, material);
lineGroup.add(curveObject);
});
scene.add(lineGroup);
1、使用new THREE.LineSegments,(LineSegments是不合并多条线段,具体介绍看官网)
2、生成一个geometry,对geometry设置position点(赋值所有的线段点)
代码如下
合并大量贝塞尔曲线
const geometry = new THREE.BufferGeometry();
const points = [];
this.bezierPathList.forEach((item) => {
const [p1, p2, p3, p4] = item.coordinate;
// 初始化数据,绘制曲线轨迹
const curve = new THREE.CubicBezierCurve3(
new THREE.Vector3(p1.x / 1000, 0.1, -p1.z / 1000), // z轴取反
new THREE.Vector3(p2.x / 1000, 0.1, -p2.z / 1000),
new THREE.Vector3(p3.x / 1000, 0.1, -p3.z / 1000),
new THREE.Vector3(p4.x / 1000, 0.1, -p4.z / 1000)
);
const curves = curve.getPoints(49); // 将线段分割为49+1个点,需要是偶数,不然会出现奇数点连接问题
curves.forEach(v => {
points.push(v.x, v.y, v.z)
})
});
geometry.setAttribute(
'position',
new THREE.Float32BufferAttribute(points, 3)
);
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff });
const line = new THREE.LineSegments(geometry, lineMaterial);
scene.add(line);
合并大量直线
const geometry = new THREE.BufferGeometry();
const paths = [];
this.linePathList.forEach((item) => {
const [p1, p2] = item.coordinate;
paths.push(
new THREE.Vector3(p1.x / 1000, 0.1, -p1.z / 1000),
new THREE.Vector3(p2.x / 1000, 0.1, -p2.z / 1000)
); // z轴取反
});
geometry.setFromPoints(paths);
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff });
const line = new THREE.LineSegments(geometry, lineMaterial);
scene.add(line);