Home > database >  How can I animate an accelerating a DOM element with JavaScript?
How can I animate an accelerating a DOM element with JavaScript?

Time:12-31

I am making an application where I need a object to move from point a to point b starting out fast but then slowing down. I want to do this with pure vanilla js and no libraries whatsoever. This is my current code for animating something at a constant speed and I was wondering if it was possible to modify it or something.

let player = document.querySelector('.player');
var id = setInterval(frame, 1);
let counter = 0;
function frame() {
    if (counter == 50) {
        clearInterval(id);
                counter = 0;
        return;
    } else {
        player.style.top = player.offsetTop - 2   'px';
        counter  
    }
}

CodePudding user response:

It would be better & easier to use CSS3 capabilities. For example you define a CSS class that has CSS transition or transform in it.e.g.

.move{
  transform: translateX(300px);
  transition: transform .3s ease-out;
}

then you simply add or remove the class using JavaScript to the DOM element you want for it to take effect. https://jsbin.com/sosuqoyasi/edit?html,css,js,output

In your case you can make the 300px a CSS variable and update it in your javascript before adding the class

if you want to have more control over the CSS in your JS code use the Web Animation API : https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API

CodePudding user response:

I would use a timeout instead of an interval with some recursion like this...

let player = document.getElementById("player")
let a = 0
const b = 500
const playerWidth = 50

animate = () => {
    a  = 20
    setTimeout(() => {
        if (a < b - playerWidth) {
            animate()
        }
        player.style.left = a
    }, a)
}

animate()

here is a working example

https://replit.com/@BenjaminKile/MoralRegularTransformations#index.html

  • Related