ThreeJS CSS 3D精灵随机化

时间:2017-12-26 14:47:47

标签: javascript html css three.js

我有点麻烦;我正在尝试调整 ThreeJS CSS 3D Sprite ,以便它为精灵使用图像数组。原文是here。这是我的代码:

  ...
  var image = document.createElement( 'img' );
  image.addEventListener( 'load', function ( event ) {
    for ( var i = 0; i < particlesTotal; i ++ ) {
      var object = new THREE.CSS3DSprite( image.cloneNode() );
      object.position.x = Math.random() * 4000 - 2000,
      object.position.y = Math.random() * 4000 - 2000,
      object.position.z = Math.random() * 4000 - 2000;
      scene.add( object );
      objects.push( object );
    }
    transition();
  }, false );
  // image.src = 'assets/img/textures/sprite.png';

  /* Randomize Images
  ============================================= */
  var imagesArray = ['assets/img/textures/orb_makro.png','assets/img/textures/orb_tiger_brands.png','assets/img/textures/orb_unilever.png'];)
  var num = Math.floor(Math.random() * 3) + 1 ;
  image.src = imagesArray[num];

  ...

我认为问题的一部分是采用一个图像的实例然后将其倍增,这就是我陷入困境的地方。非常感谢!!

1 个答案:

答案 0 :(得分:1)

要为3D精灵选择随机图像,首先要预加载所有图像:

I suppose this should help you @Hadis,

在设置部分,我们现在可以从预加载的数组中选择一个随机图像,只需添加和修改一行:

var imagesArray = [];
var urlArray = ['assets/img/textures/orb_makro.png',
                'assets/img/textures/orb_tiger_brands.png',
                'assets/img/textures/orb_unilever.png'];
var count = urlArray.length;

// load all images asynchronously
urlArray.forEach(function(url) {
  var img = new Image;
  img.onload = handler;   // todo: also add handler for onerror/onabort
  img.src = url;
  imagesArray.push(img);  // store image to preloaded array
});

function handler() {
  if (!--count) setup();  // when all images are loaded, go to setup
}

您可以选择跳过随机索引步骤,因为这些位置是随机的,只是在数组中循环:

// ...
for ( var i = 0; i < particlesTotal; i++ ) {
  var index = (Math.random() * imagesArray.length)|0; // random index
  var object = new THREE.CSS3DSprite( imagesArray[index].cloneNode() );
  object.position.set(Math.random() * 4000 - 2000,
                      Math.random() * 4000 - 2000,
                      Math.random() * 4000 - 2000);
  scene.add( object);
  objects.push( object );
}
// ...