Creating a smooth animation for drawing a line, even with just a few points, can be achieved by utilizing the LineDashedMaterial
.
The key is to render a single dash and progressively increase its length within the animation loop.
// defining geometry
var geometry = new THREE.BufferGeometry();
// setting up attributes
numPoints = points.length; // points array contains Vector3
var positions = new Float32Array( numPoints * 3 ); // 3 vertices per point
var colors = new Float32Array( numPoints * 3 ); // 3 channels per point
var lineDistances = new Float32Array( numPoints * 1 ); // 1 value per point
geometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
geometry.setAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
geometry.setAttribute( 'lineDistance', new THREE.BufferAttribute( lineDistances, 1 ) );
// populating data
var color = new THREE.Color();
for ( var i = 0, index = 0, l = numPoints; i < l; i ++, index += 3 ) {
positions[ index ] = points[ i ].x;
positions[ index + 1 ] = points[ i ].y;
positions[ index + 2 ] = points[ i ].z;
color.setHSL( i / l, 1.0, 0.5 );
colors[ index ] = color.r;
colors[ index + 1 ] = color.g;
colors[ index + 2 ] = color.b;
if ( i > 0 ) {
lineDistances[ i ] = lineDistances[ i - 1 ] + points[ i - 1 ].distanceTo( points[ i ] );
}
}
lineLength = lineDistances[ numPoints - 1 ];
// setting up material
var material = new THREE.LineDashedMaterial( {
vertexColors: true,
dashSize: 1, // to be adjusted in the render loop
gapSize: 1e10 // a large number to render only one dash
} );
// creating the line
line = new THREE.Line( geometry, material );
scene.add( line );
Then, within the animation loop:
fraction = ( fraction + 0.001 ) % 1; // fraction in [ 0, 1 ]
line.material.dashSize = fraction * lineLength;
Keep in mind: You can calculate the line distances as desired. For instance, normalizing the distances by the total length can make the distance to the last point equal to 1. In this case, you would adjust dashSize
from 0 to 1.
For an alternative method, check out this approach.
Utilizing three.js r.143