A-frame如何检测场景及资源加载完成并在控制台输出日志
A-Frame 场景与资源加载状态检测方案
你可以通过监听<a-scene>元素的内置事件来准确获取加载进度,对应你的需求可以直接使用以下方案:
核心事件说明
loaded:场景DOM结构、内置组件、基础实体初始化完成时触发,此时可能仍在加载外部资源(如3D模型、纹理贴图、音频等)render-start:所有资源(包括<a-assets>中声明的外部资源)全部加载完成,引擎准备渲染第一帧时触发,A-Frame默认的加载屏也会在此事件触发后隐藏,完全适配你自定义加载屏的需求
完整实现代码
<html> <head> <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script> </head> <body> <!-- 自定义加载屏示例,可自行修改样式 --> <div id="loadingScreen" style="position: fixed; inset: 0; background: #ECECEC; display: flex; align-items: center; justify-content: center; font-size: 24px; z-index: 9999;"> 场景加载中... </div> <a-scene id="mainScene"> <!-- 如有外部资源可统一放在a-assets标签内,会自动计入加载进度 --> <!-- <a-assets> <img id="boxTexture" src="你的贴图地址.jpg"> <a-asset-item id="customModel" src="你的模型地址.gltf"></a-asset-item> </a-assets> --> <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box> <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere> <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder> <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane> <a-sky color="#ECECEC"></a-sky> </a-scene> <script> const mainScene = document.querySelector('#mainScene'); const loadingScreen = document.querySelector('#loadingScreen'); // 场景基础结构加载完成触发 mainScene.addEventListener('loaded', () => { console.log('场景基础结构加载完成'); }); // 所有资源加载完成、准备渲染时触发 mainScene.addEventListener('render-start', () => { console.log('全部资源加载完成,场景已就绪'); // 隐藏自定义加载屏 loadingScreen.style.display = 'none'; }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Aidan Young
相关产品推荐
相关产品推荐

