Reputation: 985
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.
Upvotes: 0
Views: 5332
Reputation: 1250
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()
).
div.offsetWidth
)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.
Upvotes: 3