You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用three.js绘制Fatline,解决LineBasicMaterial的lineWidth不生效问题

问题原因

THREE.LineBasicMaterial的lineWidth属性不生效是WebGL底层实现限制导致的,绝大多数桌面、移动平台的WebGL接口仅支持1px线宽,该参数的设置不会产生预期效果。

解决方案1:使用官方FatLine拓展(推荐,适合大量点位场景)

three.js官方提供了专门的粗线条实现拓展,性能优秀,支持自定义线宽、抗锯齿、虚线样式等特性,是大量点位场景的最优选择。
首先引入对应依赖:

import { Line2 } from 'three/addons/lines/Line2.js';
import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
import { LineGeometry } from 'three/addons/lines/LineGeometry.js';

修改后的实现代码:

createLine() {
  // 初始化支持粗线的材质
  const material = new LineMaterial({
    color: 0x0000ff,
    linewidth: 10, // 线宽设置正常生效
    worldUnits: true // 可选参数,设为true线宽使用世界单位,否则为像素单位
  });

  // 点位数据需要传入扁平化的坐标数组
  const points = [-10, 0, 0, 0, 10, 0, 10, 0, 0];
  const geometry = new LineGeometry();
  geometry.setPositions(points);

  const line = new Line2(geometry, material);
  // 必须设置分辨率和画布尺寸保持一致,否则线宽显示异常
  material.resolution.set(window.innerWidth, window.innerHeight);
  scene.add(line);

  // 窗口 resize 时同步更新分辨率
  window.addEventListener('resize', () => {
    material.resolution.set(window.innerWidth, window.innerHeight);
  });
}
解决方案2:使用TubeGeometry生成3D管状线条

适合需要真实3D厚度的场景,缺点是生成的顶点数多,大量点位时性能较低:

createLineWithTube() {
  // 创建线条路径
  const path = new THREE.CatmullRomCurve3([
    new THREE.Vector3(-10, 0, 0),
    new THREE.Vector3(0, 10, 0),
    new THREE.Vector3(10, 0, 0)
  ]);
  // 参数依次为:路径、路径分段数、管线半径、径向分段数、是否闭合
  const geometry = new THREE.TubeGeometry(path, 64, 0.5, 8, false);
  const material = new THREE.MeshBasicMaterial({ color: 0x0000ff });
  const lineMesh = new THREE.Mesh(geometry, material);
  scene.add(lineMesh);
}

内容的提问来源于stack exchange,提问作者GOON

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 09:09:03