我看到A-Frame用于通过标记/ HTML构建虚拟现实体验.如何在A-Frame标记元素旁边使用JavaScript?
ngo*_*vin 13
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');
});
Run Code Online (Sandbox Code Playgroud)
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);
});
}
});
Run Code Online (Sandbox Code Playgroud)
并将这些组件以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>
Run Code Online (Sandbox Code Playgroud)
这些组件可以做任何简单的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>
Run Code Online (Sandbox Code Playgroud)
我们可以操纵各个属性:
var boxEl = document.querySelector('#box');
boxEl.setAttribute('geometry', 'width', 5);
boxEl.getAttribute('material').color;
boxEl.removeAttribute('scale');
Run Code Online (Sandbox Code Playgroud)
通过在HTML中公开其API,A-Frame适用于现有的Web框架和库,如d3,React,Angular,模板引擎.
| 归档时间: |
|
| 查看次数: |
4881 次 |
| 最近记录: |