Three.js宽线问题:线条宽度异常夸张
问题描述
参考Three.js官方宽线示例编写代码后,渲染出的线条宽度异常夸张。实现代码如下:
const newBox = mesh.geometry.clone(); const edges = new THREE.EdgesGeometry(newBox); const lines = new THREE.LineSegments( edges, new THREE.LineBasicMaterial({ color: "red" }) ); scene.add(lines); lines.applyMatrix4(mesh.matrix); lines.updateMatrix(); const pos = lines.geometry.attributes.position; const geoLine = new LineGeometry(); geoLine.setPositions( (pos.array as Float32Array).slice(0, 6) ); const matLine = new LineMaterial({ color: 0xffffff, linewidth: 1, // in world units with size attenuation, pixels otherwise vertexColors: false, dashed: false, alphaToCoverage: true, }); const line = new Line2(geoLine, matLine); line.computeLineDistances(); line.scale.set(1, 1, 1); scene.add(line);
渲染效果:
解决方案
线条宽度异常的核心原因是LineMaterial依赖画布分辨率参数,且坐标处理逻辑冗余导致矩阵同步问题,具体修复步骤如下:
- 必须设置LineMaterial的resolution参数
LineMaterial的宽度计算需要基于当前渲染画布的分辨率,未设置时会出现严重的宽度失真:
// 材质创建后立即设置分辨率 matLine.resolution.set(window.innerWidth, window.innerHeight); // 监听窗口大小变化,实时更新分辨率 window.addEventListener('resize', () => { matLine.resolution.set(window.innerWidth, window.innerHeight); });
- 简化坐标提取逻辑,同步模型矩阵
无需通过中间的LineSegments提取坐标,直接从EdgesGeometry获取顶点数据,并给Line2应用模型矩阵:
// 替换原代码中坐标提取及Line2创建的部分 const geoLine = new LineGeometry(); geoLine.setPositions(edges.attributes.position.array); const matLine = new LineMaterial({ color: 0xffffff, linewidth: 1, vertexColors: false, dashed: false, alphaToCoverage: true, }); // 关键:设置分辨率 matLine.resolution.set(window.innerWidth, window.innerHeight); const line = new Line2(geoLine, matLine); line.applyMatrix4(mesh.matrix); line.updateMatrix(); line.computeLineDistances(); scene.add(line);
- 按需调整sizeAttenuation参数
如果希望线条宽度固定为像素单位(不受相机距离影响),关闭sizeAttenuation:
const matLine = new LineMaterial({ // 其他参数不变 sizeAttenuation: false });
内容的提问来源于stack exchange,提问作者user26351712
相关产品推荐
相关产品推荐

