为了账号安全,请及时绑定邮箱和手机立即绑定

用three.js动态画线

用three.js动态画线

繁星点点滴滴 2019-09-24 16:51:31
这就是我想要实现的(一个可修改的多边形,其中红色圆圈是顶点),我想动态地构建多边形。初始化几何体时var geometry = new THREE.Geometry();geometry.vertices.push(point);geometry.vertices.push(point);var line = new THREE.Line(geometry, new THREE.LineBasicMaterial({}));它在第二次单击之前一直工作良好,它会在1和2之间建立一条直线,但是在将其推入数组时不会添加第三条线。WebGL似乎需要缓冲点。当我预先定义这样的顶点时,我可以画两条线(第三次单击)var geometry = new THREE.Geometry();for (var i = 0; i < 4; i++) {    geometry.vertices.push(point);}var line = new THREE.Line(geometry, new THREE.LineBasicMaterial({}));但这不是一个好的解决方案,因为我不知道用户想要添加多少个顶点,并且给它分配一个大数字是没有意义的,因为我必须多次循环它。有什么办法解决吗?
查看完整描述

3 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

您可以轻松地使用BufferGeometry和setDrawRange()方法为线设置动画(或增加渲染点的数量)。但是,您确实需要设置最大点数。


var MAX_POINTS = 500;


// geometry

var geometry = new THREE.BufferGeometry();


// attributes

var positions = new Float32Array( MAX_POINTS * 3 ); // 3 vertices per point

geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );


// draw range

drawCount = 2; // draw the first 2 points, only

geometry.setDrawRange( 0, drawCount );


// material

var material = new THREE.LineBasicMaterial( { color: 0xff0000 } );


// line

line = new THREE.Line( geometry,  material );

scene.add( line );

您可以使用以下模式设置位置数据:


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;


    x += ( Math.random() - 0.5 ) * 30;

    y += ( Math.random() - 0.5 ) * 30;

    z += ( Math.random() - 0.5 ) * 30;


}

如果要更改在第一次渲染后渲染的点数,请执行以下操作:


line.geometry.setDrawRange( 0, newValue );

如果要在第一次渲染后更改位置数据值,请按以下方式设置needsUpdate标志:


line.geometry.attributes.position.needsUpdate = true; // required after the first render

这是一个小提琴,显示了可以适应您的用例的动画线。


查看完整回答
反对 回复 2019-09-24
?
四季花海

TA贡献1811条经验 获得超5个赞

实时画线

这里是一个更新的小提琴,我在其中优化了 user3325025他的示例中的代码;在这种情况下,绝对不需要在渲染时更新直线的所有点。仅需要onMouseMove更新(更新行尾)和onMouseDown(绘制新点):


// update line

function updateLine() {

  positions[count * 3 - 3] = mouse.x;

  positions[count * 3 - 2] = mouse.y;

  positions[count * 3 - 1] = mouse.z;

  line.geometry.attributes.position.needsUpdate = true;

}


// mouse move handler

function onMouseMove(event) {

  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;

  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  mouse.z = 0;

  mouse.unproject(camera);

  if( count !== 0 ){

    updateLine();

  }

}


// add point

function addPoint(event){

  positions[count * 3 + 0] = mouse.x;

  positions[count * 3 + 1] = mouse.y;

  positions[count * 3 + 2] = mouse.z;

  count++;

  line.geometry.setDrawRange(0, count);

  updateLine();

}


查看完整回答
反对 回复 2019-09-24
  • 3 回答
  • 0 关注
  • 4283 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信