效果图
1.初始化场景
onMounted(() => {
line()
})
let index = 0; //取索引值的点的位置
let num = 20; //从曲线上获取的数量
let points1, newLine1, bufferGeometry1;
let points2, newLine2, bufferGeometry2;
function line() {
}
2.场景中加入一条三维曲线
function line(){
//创建一条平滑的三维曲线 给三个点 起始 中间 结尾
const drawPointList1 = new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 20, -110),
new THREE.Vector3(30, 35, -75),
new THREE.Vector3(60, 20, 0)
])
//平分为100段,分的越多曲线越丝滑
points1 = drawPointList1.getPoints(101)
// 创建曲线 设置材质
let line1 = new THREE.Line(new THREE.BufferGeometry().setFromPoints(points1), new THREE.LineBasicMaterial({ color: "#fff" })); // 构建三维曲线
// 加入场景
scene.add(line1);
}
3.截取曲线片段并渲染材质
newLine1 = new THREE.CatmullRomCurve3(points1.slice(index, index + num));//使用截取的片段点作为参数重新生成一条曲线
newLine1.getSpacedPoints(1000); //细分成100个点
var percentArr = [];
for (var i = 0; i < newLine1.length; i++) {
percentArr.push(i / newLine1.length);
}
var percentAttribue = new THREE.BufferAttribute(
new Float32Array(percentArr),
1
);
var colorArr = [];
for (var i = 0; i < 101; i++) {
var color1 = new THREE.Color(0xffffff);
var color2 = new THREE.Color(0x59BE3E);
var color = color1.lerp(color2, i / 101);
colorArr.push(color.r, color.g, color.b);
}
bufferGeometry1 = new THREE.BufferGeometry().setFromPoints(newLine1);//创建用于管理几何体的顶点数据,并设置点队列
bufferGeometry1.attributes.percent = percentAttribue;
bufferGeometry1.attributes.color = new THREE.BufferAttribute(new Float32Array(colorArr), 3);
const PointsMaterial = new THREE.PointsMaterial({ //创建点材质
size: 1.0, //点大小
vertexColors: true, //使用顶点颜色渲染
});
//加入场景
scene.add(new THREE.Points(bufferGeometry1, PointsMaterial));
4.循环执行,使线动起来
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
moveOnCurve()
}
function moveOnCurve() {
if (index <= 99) {
index += 1
bufferGeometry1.setFromPoints(new THREE.CatmullRomCurve3(points1.slice(index, index + num)).getSpacedPoints(100));
} else {
index = 0
}
}