Search code examples
javascriptaframe

Fade out whole screen in A-Frame


I would like to make the screen fade out to black, and fade it back in programmatically. I could not find a clever solution to this yet. I know I can fade in and out an entity using the material's opacity, but can you apply this to the whole screen or the camera?

Thank you


Solution

  • I'd go with a simple approach - change the opacity of a black sphere around the camera:

    <script src="https://aframe.io/releases/1.1.0/aframe.min.js"></script>
    <script>
      // declare the component
      AFRAME.registerComponent("foo", {
        init: function() {
          // grab the "fading sphere"
          var fadingEl = document.querySelector("#lord-fader")
          // when clicked - emit the defined "startEvent"
          this.el.addEventListener("click", e => fadingEl.emit("animate"))
        }
      })
    </script>
    <a-scene cursor="rayOrigin: mouse" raycaster="objects: .interactable">
      <a-text position="-0.75 2.5 -4.5" value="click to animate" color="black"></a-text>
      <a-sphere class="interactable" position="0 1.25 -5" radius="1.25" color="#EF2D5E" foo></a-sphere>
      <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
      <a-sky color="#ECECEC"></a-sky>
    
      <a-camera>
        <!-- our fake-fade sphere -->
        <a-sphere id="lord-fader" radius="0.05" 
                  material="shader:flat; color: black; opacity: 0.0; side: double " 
                  animation="property: material.opacity; from: 0.0; to: 1.0 dur: 500; dir: alternate; loop: 2; startEvents: animate"></a-sphere>
      </a-camera>
    </a-scene>


    A simpler solution could be animating a HTML element overlaid over the a-frame scene. A harder solution would be post-processing.