学习ThreeJS 03

如何创建线条

var material = new THREE.LineBasicMaterial({ color: 0x0000ff });
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(-10, 0, 0));
geometry.vertices.push(new THREE.Vector3(0, 10, 0));
geometry.vertices.push(new THREE.Vector3(10, 0, 0));
var line = new THREE.Line(geometry, material);
scene.add(line);

同一根线会包含多个点的连接, 同样创建线条也需要纹理和结构的配置

如何创建动态变化的线呢?

什么是动态变化的线: 线的长短, 线的点位置, 线的颜色

  • 如何改变点的位置
  • 如何改变线的长短(定点数)
  • 如何改变线的颜色

做到这一点, 需要用到BufferGeometry, 用于缓存3d数据

  • 创建线条
//设置线条最长缓存大小, 也就是线包括200个空间的点
var MAX_POINTS = 200;
//缓存线的结构
var geometry = new THREE.BufferGeometry();
//创建线的点数
var positions = new Float32Array( MAX_POINTS * 3 );
//加载数组到结构中 (因为一个3d空间的点由三个浮点数构成, 所以需要对数组进行标明
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
//设置渲染大小, 因为最基本的线需要两个空间的点来描述, 所以少于两个点情况下无法描述这个线条, 注意不能超过
geometry.setDrawRange( 0, 2 );
//设置材质
var material = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 2 } );
//创建线条
line = new THREE.Line( geometry,  material );
scene.add( line );

updatePositions();
  • 修改线条点属性
function updatePositions() {
    //获取点数组
    var positions = line.geometry.attributes.position.array;
    //设置临变量
    var x = y = z = index = 0;
    for ( var i = 0, l = MAX_POINTS; i < l; i ++ ) {
        //改变
        positions[ index ++ ] = x;
        positions[ index ++ ] = y;
        positions[ index ++ ] = z;
        //貌似是js的功能, 让变量能跟随变化
        x += ( Math.random() - 0.5 ) * 30;
        y += ( Math.random() - 0.5 ) * 30;
        z += ( Math.random() - 0.5 ) * 30;
    }
}

让线条渐渐显示出来

  • 更新动画
function animate() {
//持续更新动画
    requestAnimationFrame( animate );
//设置显示的线段长度变化
    drawCount = ( drawCount + 1 ) % MAX_POINTS;
    line.geometry.setDrawRange( 0, drawCount );
    if ( drawCount === 0 ) {
//更新位置点
        updatePositions();
        line.geometry.attributes.position.needsUpdate = true;
//更新线条颜色
        line.material.color.setHSL( Math.random(), 1, 0.5 );
    }
//别忘了进行渲染 renderer.render( scene, camera );
    render();
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容