Reputation: 128
I'm having a little bit of trouble; I am trying to adapt ThreeJS CSS 3D Sprite so that it use an array of images for the sprites. The original is here. Here is my code:
...
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];
...
I think part of the problem is that takes an instance of one image and then multiplies it, that's where I am getting stuck. Many thanks!!
Upvotes: 1
Views: 373
Reputation:
To pick a random image for the 3D sprite you would first preload all the images:
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
}
In the setup section we can now pick a random image from the preloaded array just adding and modifying a line:
// ...
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 );
}
// ...
You could as an option skip the random index step since the positions are random and just cycle through the array:
var object = new THREE.CSS3DSprite( imagesArray[i % imagesArray.length].cloneNode() );
Upvotes: 1