Aframe Add Preloader to image loading in sky

1.6k views Asked by At

I have a scene where I am changing the src for sky using buttons I created "outside the scene". Currently everything works fine but I would like to show a preloader while waiting for the next image to load.

Here you can see my scene: http://scriptstrainer.com/vr_training/

Below I have provided some of my code:

<a-scene>
<a-sky src="images/0-1.jpg" id="img-src">
</a-scene>
<div>
    <a href="#" id="button1"><img src="images/t1.png"></a>
</div>
<div>
    <a href="#" id="button2"><img src="images/t2.png"></a>
</div>
<div>
  <a href="#" id="button3"><img src="images/t3.png"></a>
</div>
<script>
var sky = document.querySelector('#img-src');
var button1 = document.querySelector('#button1');
var button2 = document.querySelector('#button2');
var button3 = document.querySelector('#button3');
button1.addEventListener('click', function() {
sky.setAttribute('src', 'images/0-1.jpg');
});
button2.addEventListener('click', function() {
sky.setAttribute('src', 'images/2.JPG');
});
button3.addEventListener('click', function() {
sky.setAttribute('src', 'images/3.JPG');
});   
</script>

Thanks for your assistance...

2

There are 2 answers

1
ngokevin On

https://aframe.io/docs/0.4.0/components/material.html#events_materialtextureloaded

There's an event materialtextureloaded you can use to detect when the texture has loaded onto the mesh. In between the time you request to set the texture and the time the texture is set, you can display a loading graphic.

button1.addEventListener('click', function() {
  sky.setAttribute('src', 'images/0-1.jpg');
  // Display something in the meantime.
  sky.addEventListener('materialtextureloaded', function () {
    // Small timeout just in case?
    setTimeout(function () { // Remove the placeholder. }, 100);
  });
});

The loading graphic can be like a spinning object in the scene, a fade-in black mask around the camera (as used in https://github.com/aframevr/360-image-gallery-boilerplate). It depends on what you want it to be.

0
kassemEzz On

I had the same scenario where I wanted to add a preloader and only when the image is displayed, to remove the preloader.

I tried using events 'load' and 'loaded' but didn't work as I found out images are not displayed once they finish loading.

Eventually I got help from the AFrame GitHub page and that's how I did it:

<a-assets>
  <img id='img-src' src='image.jpg'/>
</a-assets>
<a-sky src='#img-src' id='sky-id'></a-sky>

<script type='text/javascript'>
  var skyEl = document.querySelector('#sky-id');
  function loaded()
  {
    var preloader = document.querySelector('#preloader');
    preloader.style.display = "none";
  }

  skyEl.addEventListener('materialtextureloaded', loaded);
</script>