Reputation: 13
I'm trying to achieve a camera position change on scroll. I want to move the camera between 2 points on a curve depending on how much the user scrolled on the page where the three.js scene is loaded in as a fullscreen fixed background. The orbitcontrols is not going to be good here I think, because I want to trigger a movement on a camera (which has a lookat to the vector3(0,0,0)) on a bezier curve, and after the user reached the end of the scrollable content in the main div, the scene should not scroll more neither.
I saw some option for camera animation on a line in the documentation (https://threejs.org/examples/#webgl_geometry_extrude_splines), but i have no idea how to implement that on a scroll triggered base.
So if the user hasn't scrolled yet the camera in the three.js scene is on its starting point, and when the user scrolled at the end of the page, the camera moved from the starting point on a curve to the end point. So if the user is on the half of the page the camera does the same and its going to be on the half of the way.
Upvotes: 1
Views: 11645
Reputation: 2354
You need to do three things:
I assume you have no problems to place threejs canvas to the background, this part I mention in answer just for sake of completeness.
Demo: https://jsfiddle.net/mmalex/pgnz4vms/
JS Code:
function updateCamera(ev) {
let div1 = document.getElementById("div1");
camera.position.x = 10 - window.scrollY / 500.0;
camera.position.z = 10 - window.scrollY / 500.0;
}
window.addEventListener("scroll", updateCamera);
HTML Code:
<canvas id="viewport"></canvas>
<div id="div1" class="page-wrapper" >
<h3>
Three.js: Change camera position on page scroll
</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris quis vulputate neque. Proin ullamcorper nisi libero. Praesent ac tincidunt est. Pellentesque convallis tincidunt felis, non dignissim sapien dignissim nec. Donec luctus ligula ligula, ut
consectetur massa vulputate ac. Donec mattis feugiat iaculis. Fusce id leo at lectus ornare tempor. Suspendisse potenti. Praesent purus nisi, accumsan eu facilisis et, convallis et tellus. Quisque vestibulum lectus lectus, a aliquet ligula malesuada
vel. Nullam vestibulum ut sapien consectetur luctus. Aenean augue lacus, sodales sit amet tincidunt vitae, facilisis in mi. Nulla facilisi.
</p>
</div>
CSS Code:
body {
overflow-x: hidden;
overflow-y: scroll;
padding: 0;
margin: 0;
}
#viewport {
position: fixed;
margin: 0;
padding: 0;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
.page-wrapper {
padding: 0px;
margin: 12px 48px;
position: absolute;
left: 0;
top: 0;
width: calc(100% - 2*48px);
word-wrap: break-word;
}
Upvotes: 9