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

如何在Three.js中使用3D模型作为场景背景?

将3D模型作为Three.js场景背景的正确实现方式

你的代码存在两个核心问题:

  1. scene.background 仅支持颜色、Texture 或 CubeTexture 类型,不能直接赋值3D模型;且 assetsLoader.load() 是异步方法,返回值并非加载完成的模型,你在回调外访问的 model 变量根本不存在。
  2. 加载模型的逻辑是异步的,所有针对模型的操作必须放在 load 方法的回调函数内部执行。

方案一:单场景实现(推荐)

把模型作为场景的一部分,通过调整位置、缩放和渲染顺序,让它成为背景:

const assetsLoader = new GLTFLoader();

assetsLoader.load(monkeyURL.href, function (gltf) {
  const backgroundModel = gltf.scene;
  
  // 调整缩放让模型覆盖整个视野(根据模型原始尺寸和相机参数调整数值)
  backgroundModel.scale.set(50, 50, 50);
  // 将模型放在相机远平面附近,确保处于所有前景物体后方
  backgroundModel.position.set(0, 0, -100); // 对应相机far参数调整,比如你的相机far设为100就用-100
  
  // 设置渲染顺序为负数,让渲染器优先绘制背景模型
  backgroundModel.renderOrder = -1;
  
  // 让模型始终面向相机(可选,根据需求调整)
  backgroundModel.lookAt(camera.position);
  
  // 关闭背景模型的阴影计算,提升性能
  backgroundModel.traverse((child) => {
    if (child.isMesh) {
      child.castShadow = false;
      child.receiveShadow = false;
    }
  });
  
  scene.add(backgroundModel);
});

// 无需设置scene.background,模型直接作为背景元素存在于场景中

方案二:双场景渲染(适用于需要完全隔离背景与前景的场景)

创建两个场景,分别渲染背景模型和前景内容,确保背景不会被前景遮挡:

const foregroundScene = new THREE.Scene();
const backgroundScene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100);

// 加载背景模型到背景场景
const assetsLoader = new GLTFLoader();
assetsLoader.load(monkeyURL.href, function (gltf) {
  const backgroundModel = gltf.scene;
  backgroundModel.scale.set(50, 50, 50);
  backgroundModel.position.set(0, 0, -100);
  backgroundModel.lookAt(camera.position);
  backgroundScene.add(backgroundModel);
});

// 向前景场景添加你的业务物体
foregroundScene.add(yourForegroundMesh);

// 渲染循环:先绘背景,再绘前景
function animate() {
  requestAnimationFrame(animate);
  
  // 渲染背景场景
  renderer.render(backgroundScene, camera);
  // 渲染前景场景,关闭自动清除,保留背景
  renderer.render(foregroundScene, camera);
}
animate();

关键注意事项

  • 异步加载:所有模型相关操作必须在 load 回调内执行,避免访问未初始化的变量。
  • 相机参数:模型的缩放和位置需要配合相机的 fov、near、far 参数调整,确保填满视野。
  • 性能优化:关闭背景模型的阴影、减少不必要的材质计算,避免影响整体渲染性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:25:20