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

Three.js:如何实现透视3D文字穿透物体及滚动字幕?

在Three.js中实现透视3D文字穿透物体+透明背景,及滚动字幕方案

一、实现透视3D文字穿透物体且背景透明

方案1:Canvas生成透明纹理 + WebGLRenderer(推荐)

这种方案完全基于WebGL渲染,避免CSS3DRenderer的DOM层级冲突,能完美实现透明背景和穿透效果:

  • 用Canvas绘制透明背景的文字,生成Three.js纹理
  • 创建平面/立体网格,通过关闭材质的深度写入,让文字不遮挡后方物体
// 1. 生成透明背景的Canvas文字纹理
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 512;
canvas.height = 128;
ctx.fillStyle = 'rgba(0,0,0,0)'; // 透明背景
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = '60px Arial';
ctx.fillStyle = '#ff4444'; // 文字颜色
ctx.textAlign = 'center';
ctx.fillText('穿透文字', canvas.width/2, canvas.height/2);

// 2. 创建纹理与材质
const texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
const material = new THREE.MeshBasicMaterial({
  map: texture,
  transparent: true,
  depthWrite: false, // 核心:关闭深度写入,允许后方物体穿透显示
  side: THREE.DoubleSide
});

// 3. 创建文字网格并加入场景
const geometry = new THREE.PlaneGeometry(5, 1.2);
const textMesh = new THREE.Mesh(geometry, material);
textMesh.position.set(0, 0, -2);
scene.add(textMesh);

方案2:TextGeometry实现立体穿透文字

如果需要带厚度的3D文字,结合FontLoader加载字体文件实现:

const fontLoader = new THREE.FontLoader();
fontLoader.load('helvetiker_regular.typeface.json', (font) => {
  const textGeo = new THREE.TextGeometry('3D穿透文字', {
    font: font,
    size: 1,
    height: 0.2,
    curveSegments: 12
  });
  const material = new THREE.MeshLambertMaterial({
    color: 0x00ddff,
    transparent: true,
    depthWrite: false // 关闭深度写入实现穿透
  });
  const textMesh = new THREE.Mesh(textGeo, material);
  textMesh.position.set(-2, 0, 0);
  scene.add(textMesh);
});

关于CSS3DRenderer的局限

CSS3DRenderer是将DOM元素映射到3D空间,DOM元素本质是在WebGL画布的上层,即使设置background: transparent,也只能让DOM文字的背景透明,但无法让WebGL物体"穿透"DOM文字显示——这是DOM层级的本质限制,因此不建议用它实现穿透需求。

二、实现滚动字幕效果

基于WebGL文字网格,通过渲染循环更新位置实现滚动:

function animate() {
  requestAnimationFrame(animate);
  
  // 水平滚动(从右往左)
  textMesh.position.x -= 0.02;
  // 文字完全滚出视野后重置位置,实现循环
  if (textMesh.position.x < -10) {
    textMesh.position.x = 10;
  }
  
  renderer.render(scene, camera);
}
animate();

如果需要垂直滚动,修改position.y即可,可根据场景尺寸调整滚动速度和重置阈值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:22:10