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

Three.js技术问题:如何将3D模型添加到HTML画布中?

问题:Three.js无法将3D模型渲染到已有Canvas元素,附相关疑问

以下是我尝试实现功能的代码,但无法正常运行:

function main() {
            
    const container = document.querySelector( "#machine-model" );
    let height = container.offsetHeight;                    // Offset height = element + padding + border + scrollbar
    let width = container.offsetWidth;

    const fov = 75;
    const aspect = width / height;
    const near = 0.1;
    const far = 5;
    const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
    camera.position.x = 8.3;
    camera.position.y = 11.7;
    camera.position.z = -8;
    camera.lookAt( new THREE.Vector3( 0, 0, 0 ) );

    const scene = new THREE.Scene();
    scene.background = new THREE.Color( 0xFFFFFF );         // changes background color from black to white

    const ambiLight = new THREE.AmbientLight( 0xFFFFFF, 0.5 );
    scene.add( ambiLight );
    
    const spotLight = new THREE.SpotLight( 0xFFFFFF, 0.6 );
    spotLight.position.set( 13.6, 20.1, -13.9 );
    spotLight.castShadow = true;
    scene.add( spotLight );

    const gltfLoader = new THREE.GLTFLoader();
    gltfLoader.load( "model/model.glb", function( gltf ) {

        const model = gltf.scene;
        model.rotateX( -Math.PI/2 );
        console.log( model );
        scene.add( model );
        
    });

    const renderer = new THREE.WebGLRenderer( { canvas: container, antialias: true, alpha: true } );       // alpha = true -> alpha = 0
    renderer.setSize( width, height );

    function render() {

        renderer.render( scene, camera );

        requestAnimationFrame( render );

    }

    requestAnimationFrame( render );

};

main();

代码问题排查与修复

  1. 相机视距范围错误
    相机的far参数设置为5,但相机位于z=-8位置,模型在原点(0,0,0),两者距离为8,超出了far=5的视锥体范围,导致模型被裁剪无法显示。将far调整为大于8的数值即可解决,比如:

    const far = 20;
    
  2. GLTFLoader依赖缺失(若环境未配置)
    若项目未引入GLTFLoader扩展,需在Three.js核心库之后加载该模块,否则会报错无法加载模型。

关于Canvas传入Renderer的疑问

是的,当你在初始化WebGLRenderer时通过{ canvas: container }指定了页面上已存在的Canvas元素,不需要再调用appendChild方法。Renderer会直接使用你提供的Canvas进行渲染,不会自动创建新的Canvas,因此无需手动将其添加到DOM中。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:45:32