这是3D可视化教程系列的文章,如果第一次阅读请先阅读《3D可视化教程导读》

源码及3D项目文件

  源码及工程项目都放到github上。
  源码:threejs-example

效果

  可在线访问看效果10-曲线移动。实现曲线移动的效果,从一头出来,出来完整后,再从另一头开始慢慢消失。

代码说明

  原理是利用three.js提供的APIgeometry.setDrawRange来控制到底是哪些点要渲染出来:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const v0 = new THREE.Vector3( 10, 0, 0 );
const v1 = new THREE.Vector3( 0, 15, 0 );
const v2 = new THREE.Vector3( 0, 15, 0 );
const v3 = new THREE.Vector3( -10, 0, 0 );

//https://threejs.org/docs/index.html?q=curve#api/en/extras/curves/CubicBezierCurve3
const curve = new THREE.CubicBezierCurve3(v0,v1,v2,v3);

const points = curve.getPoints( 100 );
const geometry = new THREE.BufferGeometry().setFromPoints( points );

// 动态设置geometry渲染部分
// https://threejs.org/docs/#manual/en/introduction/How-to-update-things
const updateGeometry = (startVal,endVal)=>{
geometry.setDrawRange( startVal, endVal );
geometry.attributes.position.needsUpdate = true;
};

const material = new THREE.LineBasicMaterial( { color : 0xe778e7} );
const curveObject = new THREE.Line( geometry, material );

// Create the final object to add to the scene
scene.add( curveObject );

const curveMove = ()=>{
const startPoint = {val:0};
const endPoint = {val:0};

new TWEEN.Tween(endPoint)
.to({val:100},1000 * 3)
.onUpdate(()=>{
updateGeometry(startPoint.val,endPoint.val);
})
.start();

setTimeout(() => {
new TWEEN.Tween(startPoint)
.to({val:100},1000 * 3)
.onUpdate(()=>{
updateGeometry(startPoint.val,endPoint.val);
})
.start();
}, 1000 * 4);
};

curveMove();