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

能否为Three.js的TextGeometry文本对象设置背景颜色?

THREE.js TextGeometry 添加纯色背景实现方案

完全可以实现,你可以直接复用代码中已经计算好的文本边界框信息生成背景矩形,具体实现逻辑如下:

  • 利用textGeo.boundingBox获取文本的宽高尺寸
  • 生成对应尺寸的平面几何体作为背景,Z轴位置设置为略小于文本的高度,保证在文本后方不遮挡文字
  • 建议将文本和背景放在同一个THREE.Group中统一管理位移、旋转等变换,避免分别调整坐标的麻烦

修改后的完整代码如下:

const loader = new THREE.FontLoader();
const linkToFont ='link-to-font';
let textGeo;
const self = this;
loader.load(linkToFont, function (font) {
  textGeo = new THREE.TextGeometry('Hello three.js!', {
    font,
    size: 0.3,
    height: 0.01,
  });
  textGeo.computeBoundingBox();
  // 计算文本的宽高
  const textWidth = textGeo.boundingBox.max.x - textGeo.boundingBox.min.x;
  const textHeight = textGeo.boundingBox.max.y - textGeo.boundingBox.min.y;
  // 自定义背景内边距,可按需调整
  const padding = 0.05; 

  // 生成背景平面几何体,需要圆角背景可以替换为RoundedPlaneGeometry
  const bgGeometry = new THREE.PlaneGeometry(textWidth + padding * 2, textHeight + padding * 2);
  // 自定义背景颜色
  const bgMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff }); 
  const bgMesh = new THREE.Mesh(bgGeometry, bgMaterial);
  // 调整背景位置,让它和文本对齐,放在文本后方
  bgMesh.position.set(
    textGeo.boundingBox.min.x + textWidth/2,
    textGeo.boundingBox.min.y + textHeight/2,
    -0.01 // Z轴数值略小于文本高度即可,可按需微调
  );

  const textMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
  const textMesh = new THREE.Mesh(textGeo, textMaterial);

  // 用Group统一管理文本和背景,后续变换直接修改Group属性即可
  const textWithBgGroup = new THREE.Group();
  textWithBgGroup.add(textMesh);
  textWithBgGroup.add(bgMesh);
  textWithBgGroup.position.set(-100, 0, 0);
  textWithBgGroup.updateMatrixWorld();
  self.addToScene(textWithBgGroup);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:45:08