Tips for spinning a gltf model as you scroll through the webpage

I am currently working on achieving a smooth rotation of a gltf model while scrolling.
I have successfully developed a function that converts pageYOffset from pixels to radians

let scrollPositionRad = 0;
window.addEventListener("scroll",  onWindowScroll );
function onWindowScroll(){
  let scrollPosition = Math.round(pageYOffset);
  let limit = document.body.offsetHeight - window.innerHeight;  
  scrollPositionRad = (scrollPosition * 2* Math.PI) / limit;
}

as well as a function that handles the rotation and centering of the model

function centerObj(rad){
  obj.rotation.y = rad;
  let box = new THREE.Box3().setFromObject( obj );
  let center = box.getCenter( new THREE.Vector3() );
  obj.position.x += ( obj.position.x - center.x );
  obj.position.y += ( obj.position.y - center.y );
  obj.position.z += ( obj.position.z - center.z );
}

However, when I attempt to animate by calling centerObj(scrollPositionRad), the gltf model disappears

renderer.setAnimationLoop(_ => {
    centerObj(scrollPositionRad);
    renderer.render(scene, camera);
})

Here is the model loading code after creating the scene

let loader = new THREE.GLTFLoader();
let obj = null;

loader.load('https://raw.githubusercontent.com/aaadraniki/projects/web-pages/assets/models/fender_br/scene.gltf', function(gltf) {
  obj = gltf.scene;
  
  scene.add(obj);

  function centerObj(rad){
    obj.rotation.y = rad;
    let box = new THREE.Box3().setFromObject( obj );
        let center = box.getCenter( new THREE.Vector3() );
        obj.position.x += ( obj.position.x - center.x );
        obj.position.y += ( obj.position.y - center.y );
        obj.position.z += ( obj.position.z - center.z );
        }

        centerObj(0.8);

        let scrollPositionRad = 0;
    window.addEventListener("scroll",  onWindowScroll );
    function onWindowScroll(){
        let scrollPosition = Math.round(pageYOffset);
        let limit = document.body.offsetHeight - window.innerHeight;    
        scrollPositionRad = (scrollPosition * 2* Math.PI) / limit;
        }
        
  renderer.setAnimationLoop(_ => {

    centerObj(scrollPositionRad);
    renderer.render(scene, camera);
})

});

Answer №1

document.addEventListener('scroll', () => {
    scene.rotation.y = window.scrollY / 700.0;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can the Angular link function activate the change event?

I am facing an issue with my Angular directive that includes a link function. Inside this function, I am initializing a jQuery plugin which can be seen in action here: https://plnkr.co/edit/58nOhypt6FRdI4At5jwu. The problem arises when every time the dire ...

Utilizing the Google Maps JavaScript API in npm to generate route directions

After not working with Javascript for a couple of years, I decided to try loading the Google Maps Javascript API npm package in order to display a map and draw directions between two points (Lille and Biarritz, passing through Paris and Bordeaux). Unfortun ...

Activate collapsible navigation icon when clicked on a smaller screen

Seeking assistance as a newcomer to coding. Struggling to implement a responsive navbar icon that changes on small screens when clicked. Utilized a bootstrap navbar but encountering issues where clicking the navbar on a small screen only displays the list ...

Check if the data-indices of several div elements are in sequential order using a jQuery function

Is there a way to implement a function in jQuery-ui that checks the order of div elements with data-index when a submit button is pressed? I have set up a sortable feature using jQuery-ui, allowing users to rearrange the order of the divs. Here is an exam ...

Strategies for handling axios responses within a useEffect hook in Reactjs

Currently, I am working with Reactjs and implementing nextjs. I am facing an issue where I am using Axios for fetching data from an API, but I am struggling to display it on the page. To debug this, I have tried using console.log inside the useEffect fun ...

What steps should I take to execute a unique function the very first time a user scrolls to a specific element?

The issue at hand: I am working with a sophisticated looping image carousel that needs to initiate - starting from a specified initial slide - as soon as the user scrolls to a specific division. It must not restart if the user scrolls up or down and then ...

Continuously encountering the "Uncaught Error: Bootstrap dropdown requires Popper.js" message despite having already added popper.js to the code

Recently beginning my journey with Angular and Bootstrap, I decided to create a simple "hello world" app. I've included all the necessary libraries, but I encountered an error that has me stuck. Error: Bootstrap dropdown requires Popper.js I' ...

The main content will be displayed on the sub-routes of the child

I'm feeling uncertain about the routes for children. For example, I have an 'About' route with 'me' as a sub-route: { path: '/about', name: 'About', component: About, children: [ { ...

How do I search for and display a collection associated with another in Mongoose?

I am currently working on a task to locate and display all questions related to the "Question Collection" that are associated with all the surveys created by a specific user in the "Surveys Collection". Although I have successfully found questions for a pa ...

Exploring the data types of dictionary elements in TypeScript

I have a model structured like this: class Model { from: number; values: { [id: string]: number }; originalValues: { [id: string]: number }; } After that, I initialize an array of models: I am trying to compare the values with the o ...

Unable to hide jQuery form and receiving undefined function output

I seem to be facing an issue with one of the buttons. It's not functioning properly. Whenever I click on the "Add Run" button followed by the "Home" button, most functions stop working as expected. The dynamically created form doesn't hide, the ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Executing a save function in the controller when the TinyMCE save button is clicked through an Angular directive

For the Rich text editing in my angularjs application, I am using the TinyMce angular directive. The directive is working perfectly as expected. However, I wanted to include the save plugin to enable custom save functions. To integrate the save plugin, I ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA. These errors keep popping up: index.js // main Firebase file import { initializeApp } from 'firebase/app' import { getAuth } from 'firebase/auth' ...

Ways to retrieve the upcoming possible date

I'm currently working on a project using express and I need to implement a scheduling calendar. My goal is to provide users with the next available day in the format YYYY-MM-DD. Here are the rules for determining the next available day: The default ...

Establishing a Next.js API endpoint at the root level

I have a webpage located at URL root, which has been developed using React. Now, I am looking to create an API endpoint on the root as well. `http://localhost:3000/` > directs to the React page `http://localhost:3000/foo` > leads to the Next API end ...

Is there a way to simultaneously view and send this JSON data to the server using console.log?

I'm looking to inspect the JSON data being sent and received by the server, but I'm struggling to understand how promises work in this scenario. When I use console.log() on the function body, I see Promise { pending }. Unfortunately, I can' ...

Please refrain from utilizing MUI - useGridRootProps outside of the DataGrid/DataGridPro component

When we click on "Filter" in the context menu of our DataGrid, we encounter this error. We are working on implementing a component hierarchy for the DataGrid as follows: MigrationJobTable.tsx: return ( <div data-testid='migrationJobTa ...

What are the advantages of using HttpClient compared to fetch?

With the introduction of Angular 2+, HttpClient now facilitates HTTP requests sent down an RxJS observable. I'm curious about why one would opt for using HttpClient's API instead of the standard fetch for individual HTTP requests. I have a good ...