【发布时间】:2016-12-17 05:35:38
【问题描述】:
我看到 A-Frame 仅用于通过标记/HTML 构建虚拟现实体验。如何在 A-Frame 标记元素旁边使用 JavaScript?
【问题讨论】:
标签: aframe
我看到 A-Frame 仅用于通过标记/HTML 构建虚拟现实体验。如何在 A-Frame 标记元素旁边使用 JavaScript?
【问题讨论】:
标签: aframe
A-Frame 是一个 JavaScript/three.js 框架,HTML 只是最外层的声明层。
https://aframe.io/docs/0.2.0/core/entity.html
A-Frame 中的所有元素/对象都是实体。我们可以使用标准的 DOM 方法来操作这些元素。
var boxEl = document.querySelector('a-box');
boxEl.setAttribute('width', 5);
boxEl.setAttribute('color', '#FFF');
boxEl.addEventListener('click', function () {
// If we are using the cursor component.
boxEl.setAttribute('color', '#FFF');
});
boxEl.emit('some-event');
boxEl.removeAttribute('color');
boxEl.querySelectorAll('a-sphere');
var sphereEl = document.createElement('a-sphere');
sphereEl.setAttribute('radius', 1);
document.querySelector('a-scene').appendChild(sphereEl);
sphereEl.addEventListener('loaded', function () {
console.log('sphere attached');
});
https://aframe.io/docs/0.2.0/core/
A-Frame 建立在实体-组件-系统模式 (ECS) 之上,在游戏开发中很流行,并用于 React 和 PlayCanvas 等引擎。在 ECS 中,每个对象(或实体)都是通过组合组件从头开始创建的(不要与 Web 组件混淆)。组件为实体添加逻辑、行为、外观。
https://aframe.io/docs/0.2.0/core/component.html
我们可以将JS封装在组件中:
AFRAME.registerComponent('color-on-click', function () {
schema: {
color: {default: 'blue'}
},
init: function () {
var el = this.el; // Reference to the entity.
var data = this.data; // Data passed in through HTML, defined in schema.
el.addEventListener('click', function () {
el.setAttribute('color', data.color);
});
}
});
并将这些组件附加到 HTML 中的实体上。请注意我们是如何以声明方式将 JS 附加/插入到 HTML 中的对象,这些对象可以接受输入!:
<a-box color="red" color-on-click="color: blue"></a-box>
<a-sphere color="orange" color-on-click="color: white"></a-sphere>
而这些组件除了简单的 JS 之外还可以做任何事情。我们可以访问整个three.js API,因此可以轻松包装 three.js 中的任何内容。事实上,我们将世界上任何我们想要的 JS 库包装在组件中,并以声明方式使用它们。
操作组件的属性类似于操作 HTML 属性。 <a-box> 由几何和材料组件组成。所以它看起来像在引擎盖下:
<a-entity id="box" geometry="primitive: box" material="color: red" scale="2 2 2"></a-entity>
我们可以操纵各个属性:
var boxEl = document.querySelector('#box');
boxEl.setAttribute('geometry', 'width', 5);
boxEl.getAttribute('material').color;
boxEl.removeAttribute('scale');
通过在 HTML 中公开其 API,A-Frame 可以很好地与现有的 Web 框架和库(如 d3、React、Angular、模板引擎)配合使用。
【讨论】: