透過 Sketchfab 下載完 3D 模型後就可以在 three.js 的世界裡匯入
先在 ejs 處匯入函式庫,要注意的是 GLTFLoader 的版本要與 Three.js 版本相同,否則會報錯
<script src="https://unpkg.com/three@0.128.0/examples/js/loaders/GLTFLoader.js"></script>
參照官網範例匯入 3D 模組,可以選擇 GTLF 或 GLB
var load_flag = false
function gltf_loader(){
// 載入 loader
const loader = new THREE.GLTFLoader()
// Load a glTF resource
loader.load(
'gltf/dog_gltf/scene.gltf',
// 'gltf/dog_glb/playful_dog.glb',
// called when the resource is loaded
function ( gltf ) {
gltf = gltf
dogObj = gltf.scene
dogObj.rotation.y = Math.PI / 8;
dogObj.position.y = 0;
dogObj.scale.set(10, 10, 10);
// 設定陰影
dogObj.traverse(function(object) {
if (object instanceof THREE.Mesh) {
object.castShadow = true
object.receiveShadow = true
scene.add(dogObj);
load_flag = true
console.log(gltf)
// called while loading is progressing
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
// called when loading has errors
function ( error ) {
console.log( 'An error happened:'+error );
透過 console.log
輸出,可以查看到 GLTF 所有屬性
init() 處將物件加入場景
function init() {
gltf_loader()
將原本掉落的球更改成 gltf 物件
function animate() {
if (load_flag){
// 複製剛體位址到物體位置
dogObj.position.copy(sphereBody.position)
dogObj.quaternion.copy(sphereBody.quaternion)
Render 處新增 requestAnimationFrame(animate)
,將 3D 模型加入渲染畫面
function render() {
world.step(fixedTimeStep)
statsUI.update()
cameraControl.update()
requestAnimationFrame(animate)
requestAnimationFrame(render)
renderer.render(scene, camera)
Day18 Demo | Github
修改完後就可以看到原本掉落的球體,已經被換成匯入的 3D 模型了
Reference
https://threejs.org/docs/?q=glt#examples/en/loaders/GLTFLoader
https://discourse.threejs.org/t/gltf-loader-not-working-anymore/33425/2