用three.js动态画线

这就是我想要实现的(一个可修改的多边形,其中红色圆圈是顶点),我想动态地构建多边形。

http://img4.mukewang.com/5d89d92d000139ba03370245.jpg

初始化几何体时


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({}));

但这不是一个好的解决方案,因为我不知道用户想要添加多少个顶点,并且给它分配一个大数字是没有意义的,因为我必须多次循环它。


有什么办法解决吗?


繁星点点滴滴
浏览 4287回答 3
3回答

HUWWW

您可以轻松地使用BufferGeometry和setDrawRange()方法为线设置动画(或增加渲染点的数量)。但是,您确实需要设置最大点数。var MAX_POINTS = 500;// geometryvar geometry = new THREE.BufferGeometry();// attributesvar positions = new Float32Array( MAX_POINTS * 3 ); // 3 vertices per pointgeometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );// draw rangedrawCount = 2; // draw the first 2 points, onlygeometry.setDrawRange( 0, drawCount );// materialvar material = new THREE.LineBasicMaterial( { color: 0xff0000 } );// lineline = new THREE.Line( geometry,&nbsp; 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 ++ ) {&nbsp; &nbsp; positions[ index ++ ] = x;&nbsp; &nbsp; positions[ index ++ ] = y;&nbsp; &nbsp; positions[ index ++ ] = z;&nbsp; &nbsp; x += ( Math.random() - 0.5 ) * 30;&nbsp; &nbsp; y += ( Math.random() - 0.5 ) * 30;&nbsp; &nbsp; z += ( Math.random() - 0.5 ) * 30;}如果要更改在第一次渲染后渲染的点数,请执行以下操作:line.geometry.setDrawRange( 0, newValue );如果要在第一次渲染后更改位置数据值,请按以下方式设置needsUpdate标志:line.geometry.attributes.position.needsUpdate = true; // required after the first render这是一个小提琴,显示了可以适应您的用例的动画线。

四季花海

实时画线这里是一个更新的小提琴,我在其中优化了 user3325025他的示例中的代码;在这种情况下,绝对不需要在渲染时更新直线的所有点。仅需要onMouseMove更新(更新行尾)和onMouseDown(绘制新点):// update linefunction updateLine() {&nbsp; positions[count * 3 - 3] = mouse.x;&nbsp; positions[count * 3 - 2] = mouse.y;&nbsp; positions[count * 3 - 1] = mouse.z;&nbsp; line.geometry.attributes.position.needsUpdate = true;}// mouse move handlerfunction onMouseMove(event) {&nbsp; mouse.x = (event.clientX / window.innerWidth) * 2 - 1;&nbsp; mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;&nbsp; mouse.z = 0;&nbsp; mouse.unproject(camera);&nbsp; if( count !== 0 ){&nbsp; &nbsp; updateLine();&nbsp; }}// add pointfunction addPoint(event){&nbsp; positions[count * 3 + 0] = mouse.x;&nbsp; positions[count * 3 + 1] = mouse.y;&nbsp; positions[count * 3 + 2] = mouse.z;&nbsp; count++;&nbsp; line.geometry.setDrawRange(0, count);&nbsp; updateLine();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript