AFrame(a-frame)是Mozilla推出的基于Three.js的一个WebXR ( WebVR ) 应用开发引擎。
其架构或设计模式为游戏引擎常用的Entity/Component/System。其总体思想是通过声明式语言的方式来创建实体、挂载组件,并通过系统(Systems)来提供基础服务如多相机系统、XR交互控制、存储系统等。
其工作过程大致如下:
1)在DOM文档中声明a-scene,a-box等元素
2)使用Web Component API的生命周期函数来创建和初始化对应于dom元素的three场景和3d对象
生命周期函数有:[ 'attachedCallback', 'attributeChangedCallback', 'createdCallback', 'detachedCallback' ]
比如在a-scene元素的createdCallback函数中,相应的创建一个three.js里的Scene对象:this.object3D = new THREE.Scene();
同时通过属性来设置一些默认的组件(Components):// Default components.
this.setAttribute('inspector', '');
this.setAttribute('keyboard-shortcuts', '');
this.setAttribute('screenshot', '');
this.setAttribute('vr-mode-ui', '');
在setAttribute函数里面会调用组件(Comopnent)的初始化方法:// Component not yet initialized. Initialize component.
this.initComponent(attr, attrValue, false);
而在box(a-entity)元素的createdCallback函数中,创建一个object3d,在attachedCallback回调中添加到父节点中(可以是scene节点或者其他entity节点)this.addToParent();
3)在a-scene的attachedCallback中初始化系统(Systems)this.initSystems();
经过上面3个步骤,整个three.js的场景空间(场景树、节点、节点上附属的功能组件、相机系统等)已经基本构造完毕。
4)使用three.js的render循环来完成渲染renderer.render(this.object3D, this.camera);