I want to make an animation, like in roulette (or as a spinning drum, or as in a casino), that is, the animation should start quickly and gradually, gradually complete. I tried through cubic-bezier , the result was not satisfactory, the animation turned out to be jerky ... I tried it using pure js, recursion, but I don’t agree with my ideas:

 var timer = null; var sec = 1000 / 80; var target = document.getElementById('box'); var dis = target.offsetLeft; document.onclick = function(){ function anim(t){ timer = setInterval(function(){ dis += 1; target.style.left = dis + 'px'; if(target.offsetLeft >= 100) { clearInterval(timer); anim(sec+=10) } }, t); } anim(sec); } 
 #box { background: red; color: #fff; width: 200px; padding: 10px 0; position: absolute; } 
 <div id="box">OK</div> 

Tell me how to properly implement such an animation?

    2 answers 2

    Something like this, but I would use a different increment function. And the stop condition needs to be set. You have used both recursion and spacing at the same time. What spawned inappropriate behavior.

    If something is not clear - ask

     var sec = 20; var target = document.getElementById('box'); var dis = target.offsetLeft; document.onclick = function(){ function anim(t){ setTimeout(function(){ dis += 1; target.style.left = dis + 'px'; anim(sec*=1.05) }, t); } anim(sec); } 
     #box { background: red; color: #fff; width: 200px; padding: 10px 0; position: absolute; } 
     <div id="box">OK</div> 

       console.clear(); const anim = document.getElementById('anim'); anim.onclick = () => { let velocity = 10; let path = 0; let acceleration = 0.11; let timer = setInterval(() => { path += velocity; velocity -= acceleration; anim.style.left = path + 'px'; if(velocity <= 0) clearInterval(timer); }, 35); }; 

      Jsbin

      We move an element based on its velocity , which decreases with time.

      In the end, it creates a feeling of slowing down.

      The time after which the animation will be called up can be adjusted, for a smoother picture (30-50 is the most)

      • Thank! I understand the mechanism. I did everything wrong. And what if the x coordinate is fixed? That is, for example, the element needs to be moved to 300px using this animation? - Ghost