问题描述
三个js的新手.探索使用线段.我正在尝试确定一行的长度.我正在使用computeLineDistances();获得线长的方法.该线沿x轴绘制,以x = 10结尾.由于某些原因,日志控制台返回零值.是否有人解释了为什么控制台中返回的长度= 0;
New to three js. Exploring working with line segments. I'm trying to determine the length of a line. I'm using the computeLineDistances(); method to get the line length. The line is drawn along the x-axis ending at x=10. For some reason the log console returns a zero value. Does anyone have an explanation why the length returned in the console = 0;
var myLength =0 ;
//a line start point (0,0,0), end point (10,0,0)
var points = []; // x, y, z
points.push( new THREE.Vector3( 0, 0, 0 ) ); // start point
points.push( new THREE.Vector3( 10, 0, 0 ) );
var geometry = new THREE.BufferGeometry().setFromPoints( points );
var axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
drawLine(); //call the line drawing function
// function to draw a line
function drawLine () {
var line = new THREE.Line( geometry, material );
scene.add( line );
//var myLength = line.distanceTo();
var myLength = line.computeLineDistances();
//return (line);
} // end function drawLine
//log
console.log("myLength: ", myLength);
下面是小提琴链接:
https://jsfiddle.net/kdwoell/kgm6j1q4/
推荐答案
如果您想知道行的总长度,则在调用 .computeLineDistances()
在非索引缓冲区几何中,您可以从中获取:
If you want to know the total length of line, then, after calling .computeLineDistances()
on a non-indexed buffer geometry, you can get it from:
line.geometry.attributes.lineDistance.array [length_of_points_array-1]
或
line.geometry.attributes.lineDistance.getX(line.geometry.attributes.lineDistance.count-1);
很快:
var ld = line.geometry.getAttribute("lineDistance");
console.log(ld.getX(ld.count - 1));
示例:
body {
overflow: hidden;
margin: 0;
}
<script type="module">
import * as THREE from "https://threejs.org/build/three.module.js";
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 100);
camera.position.set(0, 0, 20);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
var pts = [
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(10, 0, 0),
new THREE.Vector3(10, 10, 0)
];
var geom = new THREE.BufferGeometry().setFromPoints(pts);
var mat = new THREE.LineBasicMaterial({color: "yellow"});
var line = new THREE.Line(geom, mat);
line.computeLineDistances();
var ld = line.geometry.getAttribute("lineDistance");
console.log("line's total length: " + ld.getX(ld.count - 1));
scene.add(line);
renderer.setAnimationLoop(()=>{
renderer.render(scene, camera);
});
</script>
这篇关于三个JS-为什么线长等于零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!