一、 Line, LineLoop, LineSegments
参考 深入理解Three.js中线条Line,LineLoop,LineSegments
看生成的图片,就知道差别了,4个点的位置如下:
geometry.vertices.push(
new THREE.Vector3(20,20,0),
new THREE.Vector3(20,-20,0),
new THREE.Vector3(-20,-20,0),
new THREE.Vector3(-20,20,0)
)
- Line会从第一个点至最后一个点,依次连接起来。
- LineLoop和Line的区别在于,会自动把最后一个点和第一个点连结起来。
- LineSegments会把两个点变成一组连接起来。
LineSegments. LineSegments用于将两个点连接为一条线,它会将我们传递的一系列点自动分配成两个为一组,然后将分配好的两个点连接。
二、虚线
参考
three.js 04-10 之 LineDashedMaterial 材质
lines.computeLineDistances();
var lineMaterial = new THREE.LineDashedMaterial({
vertexColors: true,
color: 0xffffff,
dashSize: 0.6,
gapSize: 0.2,
scale: 1.0 // 比例越大,虚线越密;反之,虚线越疏
});
- scale (缩放比例) 缩放 dashSize 和 gapSize。如果 scale 小于 1,dashSize 和 gapSize 就会增大;反之,就会缩小
- dashSize (短划线长度) 定义虚线短划线的长度
- gapSize (间隔长度) 定义虚线间隔的长度
参考
https://github.com/mrdoob/three.js/blob/dev/src/materials/LineDashedMaterial.js
this.scale = 1;
this.dashSize = 3;
this.gapSize = 1;
三、注意geometry版本差异
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 material = new THREE.LineBasicMaterial({ color: 0x0000ff });
var line = new THREE.Line(geometry, material);
scene.add(line);
但是,这段代码报错了:
Uncaught TypeError: THREE.Geometry is not a constructor
参考Three.js 新旧版本创建几何对象差异,发现是版本升级导致的,新代码是这样的:
let start = new THREE.Vector3(7, 1.8, -2);
let end = new THREE.Vector3(1.6, 1.8, -2);
let lineMaterial = new THREE.LineBasicMaterial({ color: 0x00ff00 });
let pointsArray = [start, end];
let lineGeometry = new THREE.BufferGeometry().setFromPoints(pointsArray);
let line = new THREE.Line(lineGeometry, lineMaterial);
scene.add(line);
在 three.js画线,报错THREE.Geometry is not a constructor中,有评论说125版本就不再支持这个api了,类似有这样的写法:
var geometry = new THREE.BufferGeometry();
var vertices = new Float32Array( [-10, 0, 0, 0, 10, 0, 10, 0, 0] );
geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
四、默认threejs的线宽是无法调节的,需要用有厚度的线 THREE.Line2
参考
THREE.js(二):设置材质线条宽度(lineWidth) 无效
关于 ThreeJS 线宽 lineWidth 无法正常显示 太大 需要缩小 窗口缩放会影响线粗细 等问题
官方示例:
https://threejs.org/examples/?q=line#webgl_lines_fat
https://github.com/mrdoob/three.js/blob/master/examples/webgl_lines_fat.html
/** 添加线条宽度测试*/
private addLineTestCode(): void {
// 1. 赋值空间点坐标,三个一组
var pointArr = [0, 0, 0, 0, 10, 0];
// 2. 创建 LineGeometry,并设置空间点
var geometry = new LineGeometry();
geometry.setPositions(pointArr);
// 3. 创建 LineMaterial,设置颜色和线宽
var material = new LineMaterial({
color: 0xff0000,
linewidth: 15
})
// 4. 设置材质分辨率
material.resolution.set(window.innerWidth, window.innerHeight);
// 5. 创建 Line2
var line = new Line2(geometry, material);
// 6. 计算下线条长度
line.computeLineDistances();
// 7. 添加到场景
this.scene.add(line)
}
五、鼠标离线有一定距离时就响应交互(射线检测的threshold属性)
官方示例
https://threejs.org/examples/?q=lines#webgl_interactive_lines
raycaster = new THREE.Raycaster();
raycaster.params.Line.threshold = 3;
其他参考:
THREE.js开荒小记(二):无效宽度linewidth的Line 和 无效阔threshold的Line2