Animate moving between two points over a set period using JavaScript

My attempt to smoothly move a box from one position to another using Linear Interpolation is not working as expected. The box just moves without any easing effect. I came across a post on Stack Overflow titled C# Lerping from position to position, but I may be misinterpreting the equation provided. Here is my current code:

const lerp = (start, end, speed) => start + (end - start) * speed

const div = document.querySelector('div')
const btn = document.querySelector('button')

let pos = 0
let startTime = 0
const duration = 2000
let aF = null

const animate = () => {
  const elapsed = Date.now() - startTime
  const t = elapsed / duration

  if(elapsed < duration) {
    pos = lerp(0, 300, t)
    aF = requestAnimationFrame(animate)
  } else {
    cancelAnimationFrame(aF)
    aF = null
    pos = 300
  }

  console.log(pos, 300 * t)

  div.style.transform = `translateX(${pos}px)`
}

btn.addEventListener('click', () => {
  pos = 0
  startTime = Date.now()
  aF = requestAnimationFrame(animate)
})
div {
  width: 50px;
  height: 50px;
  background: green;
}

button {
  margin-bottom: 10px; 
}
<button>Run Animation</button>

<div></div>

In the code example above, the box animates without any easing effect. The values in the console logs remain the same even though the intention was to apply linear interpolation on one value and not the other.

I'm aware that there might be something I'm missing or misunderstanding here. Any assistance or insight would be greatly appreciated. Thank you.

Answer №1

It seems like your example code is functioning as expected (a + (a-b) * t). However, the crucial element of interpolation appears to be missing. Interpolation involves the process of reassigning a value (t in this context) from a range of 0-1 to another range of 0-1 using a different function (thus transforming a + (a-b) * t into a + (a-b) * interpolate(t)). There are countless possible functions that can be utilized for this purpose, and I have incorporated some popular ones into your provided example:

let interpolators = {
            identity: function(t){
                t = Math.max(0,Math.min(1,t));
                return t;
            },
            cubic: function(t){
                t = Math.max(0,Math.min(1,t));
                if(2*t<<0){
                    return 4*(t-1)*(t-1)*(t-1)+1;
                } else {
                    return 4*t*t*t;
                }
            },
            elastic: function(t){
                t = Math.max(0,Math.min(1,t));
                var range = 10.5*Math.PI;
                return (range - Math.sin(range*t)/t)/(range - 1);
            }
        };

The crux of the modification lies in:

const t = interpolators[selected](elapsed / duration);

https://jsfiddle.net/ibowankenobi/6ctp9a0s/26/

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

Include a function call within a ternary operator in JSX code

I am looking to call a function within a ternary operator condition. Here is what my code looks like: {snapshot.Bid[0].Price !== 'undefined' ? `(${initialOrderInfo.snapshot.Bid[0].Price}` {renderCurrencySymb ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

Tips for maintaining space beneath an image when text wraps around it

.blogimgarea { width: 38%; padding-right: 26px; float:left; } img{max-width:100%} .blogtextarea { width:55%; padding:22px 32px 0 0; float:right; } <div class="newpostregion pt70"> <div class="blogimgarea"> <img class="featblogimg" src="https ...

Error: Attempting to insert or update the "tokens" table violates the foreign key constraint "tokens_userId_fkey" in Sequelize

I am facing an issue that I can't seem to resolve, as I keep encountering an error related to a constraint violation. The tables involved in this problem are Token and User, which are linked through the userId column. The error occurs when I try to cr ...

How can you create a basic click event for a Google Maps marker?

Can a straightforward action be triggered using jQuery or JavaScript when a user clicks on a Google Maps marker? I am attempting to load content into an external div using AJAX when a user clicks on a marker on the map. The following code snippet could se ...

Performing a task after a process has finished

Currently, I'm working with node JavaScript and facing an issue where I need to run a new function after a loop has completed. In the code snippet provided below, // loop through objects in data, to process it represents a basic for loop iterating ove ...

The jQuery .load() function does not seem to be functioning properly on secure HTTPS connections

After implementing an SSL certificate through Cloudflare on my website, I encountered an issue where a specific function returned an error code 0 and failed to load the URL content. How can I resolve this issue? $(function () { EnderReact(); }); functi ...

Troubleshooting angular radio input display issue caused by controller updates

When the page loads, my AngularJS controller.js initializes the scope model by fetching data from an AJAX response: services.InitializePage().then(function (response) { $scope.DataModel = response.data; Shortly after that, the model undergoes ...

Exploring nested objects and arrays with Plunker - extracting their values

I have retrieved two arrays, each containing nested objects, from API endpoints. One array (preview) consists solely of numbers. For example: [{ obj1:[1, 2], obj2:[3, 4] }] To obtain strings associated with IDs, I made another call to a different en ...

What steps can be taken to restrict a user's access to the main page unless they are logged in?

I have created sign up and login pages using JavaScript, HTML, and PHP with a database. After a user successfully logs in on the login page, the following code is executed: sessionStorage.setItem('logged','loggedIn'); The user is then ...

What is the best way to call the app.js function from an HTML page in an Express.js environment

Is there a way to trigger the function init() { // } located in app.js from an HTML page? <a href='javascript:init();'> Trigger init </a> The issue with the code above is that it searches for function init() only on the client side ...

Load a form using ajax and submit it using jQuery

For a while now, I have been facing challenges in figuring out what's going wrong with my code. The issue arises when I try to submit a form using jQuery that was loaded through ajax. The form loads perfectly fine within a div after invoking the ajax ...

Momentjs initially indicates that the date is valid, logs the correct date, and displays the accurate duration using .fromNow(). However, this suddenly switches

I am currently working on converting the createdAt date in my Nuxtjs application that is fetched from MongoDB using an express app, with the help of moment.js. Initially, when I check if the date is valid, it shows as valid but then it switches to an incor ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

Encountered an error while executing findByIdAndRemove operation

Could someone please assist in identifying the issue with the mongoose findByIdAndRemove function in the delete route provided below? //DELETE Route app.delete("/blogs/:id", function(req, res){ //Delete blog Blog.findByIdAndRemove(req.params.id, funct ...

Capture the Promise Rejection

During my test with WebdriverIO, I consistently encounter an issue specifically with this line of code: await browser.waitForVisible('#tx-sent li', 15000) Intermittently, a Promise rejection error occurs: Error: Promise was rejected with the ...

Styling elements with CSS

I've been attempting to align a button to the right of another button. The example above illustrates what I'm trying to achieve. I used Bootstrap to build it, which has a useful navbar feature for layout. However, despite my efforts to use right ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

Using Vue.js to submit a form in Laravel and redirecting with a flash message

I am facing an issue where I have two components named Index and Create, loaded from separate blade files. The challenge is passing a flash message as a prop between these components due to their file separation. How can I redirect after submitting a form ...

Is there a more concise method to reference the parent scope in AngularJS in this scenario?

Is there a shorter way to reference the parent scope within this controller? $scope.tables = []; $scope.newTable = function(){ $scope.tables.push({name:"Table " + ($scope.tables.length+1),cols:[]}); $scope.selected = $scope.tables.length-1; }; I ...