简体   繁体   中英

Three.js: How to do a fade scene transition?

I can't seem to find a standard way to animate the switching between the current rendered scene in Three.js. I have simplified my implementation as follows:

var sceneIndex;
var currentScene;

switch (sceneIndex) {
   case 1:
          currentScene = scene;
          break;
   case 2:
          currentScene = scene1;
          break;
}

And when I want to switch the scene:

if (clickEvent) {
   sceneIndex = 2
} 

The scene is rendered like this:

renderer.render(currentScene, camera); //I use only one camera

Right now, this produces a sudden cut off to the next scene which is not user friendly. What I want is a simple fade to black animation when the variable currentScene changes. What way would you suggest to achieve this? Thanks.

You could do this without the need of Three.js. Just place a div covering the canvas and animate it to fade to black screen and back. You wait half the time the animation takes and change the screen at that point (using setTimeout() ).

Step-by-step process:

  • Place a div on top of your canvas (you should be using absolute positioning )
  • Add a CSS class that includes an animation (see example below)
  • Setup the keyframes for the animation (see example below)
  • Trigger then animation by:
    1. Remove the class from the element
    2. Act on the element (eg div.offsetWidth )
    3. Add the class to the element

The animation will trigger when an element has the class. Then, it will play until it finishes or the element loses the class, whatever comes first.

Here's an example:

 var color = "#0000FF"; function changeScene() { // Trigger animation var div = document.getElementById("curtain"); div.classList.remove("screen-change"); div.offsetWidth; div.classList.add("screen-change"); // Trigger scene change setTimeout(function() { // Your real code should go here. I've added something // just to demonstrate the change color = color == "#0000FF"? "#FF0000" : "#0000FF"; document.getElementById("render").style.background = color; }, 1000); }; 
 div { width: 160px; height: 90px; } #render { background: #0000FF; } #curtain { background: black; opacity: 0; } .screen-change { animation-name: screen-change; animation-duration: 2s; } @keyframes screen-change { 0% {opacity: 0;} 30% {opacity: 1;} /* Waiting time */ 70% {opacity: 1;} 100% {opacity: 0;} } 
 <div id="render"><div id="curtain"></div></div> <button id="scene-changer" onclick="changeScene()">Change scene</button> 

This solution is very cheap (it uses CSS animations, which are supported by most major browsers ) and looks very nice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM