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

What is the best way to conduct a conditional check across all subsequent visible rows of a table?

When a user clicks inside the text input field and presses either the down or up arrow keys, my JavaScript function is triggered. The purpose of this functionality is to search table values and allow the user to select one by pressing the arrow keys. Every ...

Tailored Filtering and Sorting Features for Material Table

In the table, there is a column labeled Active which contains data represented as 1 or 0 for active and inactive states. Instead of displaying the values as 1 or 0, a function called generateFlagText uses the render prop to show an MUI Chip component base ...

Leverage Typescript to convert string literal types to uppercase

type x = 'first' | 'second' I am looking to create a type y that is similar to this: type y = 'FIRST' | 'SECOND' Here is what I attempted: type x = 'first' | 'second' type y = {[key in x]: key[& ...

Is it possible to utilize the node package ssh2 within a web browser environment?

I am working on a project for school where I am creating an SFTP client directly in my browser. I have successfully implemented the node package ssh2 and it works perfectly when running the code in the terminal. I can connect to the server, read directorie ...

Draggable slider not functioning properly with linear interpolation

Recently, I've been delving into the world of "linear interpolation" and its application in creating easing effects. However, while the easing functionality of the draggable slider seems to be operational, I'm encountering an issue. The slider re ...

Navigating through pages in a server component using Next.js

I am currently working on a project that involves implementing pagination using the NextJS 13 server component without relying on the use client. The goal is to ensure that when a button is clicked, new entries are added to the screen in a sequential order ...

Leveraging Flask to pass data to Google Charts with JavaScript

Trying to integrate Google Charts on my website using Flask as the backend. Need help with sending data from Flask to JavaScript. Here's a snippet of where I plan to retrieve data later: @app.route("/") def home(): data = {'Language': &a ...

JavaScript and CSS tabs with smooth transition effect

I want to create tabs that smoothly fade between each other when switching. The code I have works, but there's a slight issue. When transitioning from one tab to the previous one, there is a momentary glitch where the last tab briefly changes state be ...

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Utilizing Bootstrap to allow for seamless text wrapping around a text input field

I am trying to implement a "fill-in-the-blank" feature using Bootstrap, where users need to enter a missing word to complete a sentence. Is there a way to align the text input horizontally and have the rest of the sentence wrap around it? This is my curr ...

What is the best way to send two Array objects through http requests in AngularJS?

Is there a way to receive two parameters as an array in an HTTP action, like List `abc` and List `xyz`, and then use a model class? public class ItemAndChecque { public List<SaleItem> saleitem { get; set; } public List<itemChecqe> item ...

Encountering an isObject issue while using the @material/core package

When attempting to run the project, I encountered this error in the console: isobject error Upon inspecting the package-lock.json file, I discovered that the isobject dependency was missing in @material-ui/core. Adding it manually resolved the issue. pac ...

Determining where to implement the API display logic - on the server side or

Currently, I am in the process of restructuring an API that deals with user profiles stored in one table and profile images in another. The current setup involves querying the profiles table first and then looping through the images table to gather the ass ...

Once the ajax request is finished, load only the <script> tags that have specific ids

I'm currently implementing infinite-scroll to dynamically load more content which includes <script> tags that need to be executed. To achieve this, I have created the following code as an ajax-callback: JS on load ajax callback: function a ...

Guide on integrating Select2 with webpack

I recently acquired the select2 node module with this command: npm install select2 After adding it to my app.js: require('select2')($); Although no errors appear when I use webpack, upon opening the application, I encounter: Uncaught TypeEr ...

What is the best way to assign user input to my JavaScript variables?

As a newcomer to programming, I am eager to develop an app that utilizes the numerical values inputted by customers as variables for calculations. How can I extract the value from an input using JavaScript? For instance, how can I subtract one input value ...

Does SameSite=Lax grant permission for GET requests from third-party sources?

After exploring the MDN documentation on SameSite=Lax, I have come to understand the following: In modern browsers, cookies can be sent along with GET requests initiated by a third-party website or during top-level navigations. This is the default behav ...

Mastering the art of utilizing middleware in every HTTP request using Node.js Express

I am currently developing a middleware for my nodejs application and I need to include a header in the request within the middleware before sending it to my index.js endpoint. middleware1.js exports.mw1 = function(req, res, next) { next(); }; middlewa ...

Generating Multilayered PDF files with JavaScript in NodeJS

After reviewing the documentation for PDFMake, PDFKit, and WPS: PostScript for the Web, I couldn't find any information beyond background layers. It seems like Optional Content Groups might be what I need, but I'm unsure how to handle them using ...

Chrome extension: some APIs disappear after chrome.runtime.reload() is called

Issue with my Chrome Extension involving the chrome.tabs API. Extension runs smoothly, but encounters a problem after chrome.runtime.reload(); occasionally, the chrome.tabs reference becomes undefined upon restart. This renders the extension unusable and ...