使用A-frame的'set”组件将球体颜色设置为一个变量,在HTML中使用变量名来设置颜色属性。代码示例如下:

HTML

JS:

AFRAME.registerComponent('color-changer', { init: function () { this.el.setAttribute('material', 'color', 'red'); // 初始颜色设为红色 var self = this;

// 2秒后将颜色变为绿色
setTimeout(function () {
  self.el.setAttribute('material', 'color', 'green');
}, 2000);

// 4秒后将颜色变为蓝色
setTimeout(function () {
  self.el.setAttribute('material', 'color', 'blue');
}, 4000);

// 6秒后动态生成一个随机颜色,将my_color变量赋值为该颜色
setTimeout(function () {
  var randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
  self.el.setAttribute('material', 'color', randomColor);
  self.el.sceneEl.setAttribute('my_color', randomColor);
}, 6000);

} });