Jump to content

Recommended Posts

Posted

Boas, tenho dificuldades em fazer uma animação em javascript.. Preciso que um div percorra uma parabola do tipo: -1.3x^2 em que x é o margin-left do div relativo ao seu start position e o resultado é a curvatura do div.

for (var x=-5; x<=7; x++)
{
  document.getElementById('box').style.top=parseInt(document.getElementById('box').style.top)+(1.3 * x ^ 2);
  setTimeout(function () {},100);
}

tenho este código que supostamente faria o div percorrer uma parabola em 12 pontos diferentes. Mas o que acontece é que salta logo para a posição final...

Alguém sabe uma forma de o div parar em cada ponto da função?

Agradeço qualquer tipo de ajuda 🙂

Posted (edited)

Vê se ajuda...



<!DOCTYPE html>
<html>
<head><title>animação</title>

<style>
#boneco {
   width: 50px;
   height: 50px;
   border: 1px solid green;
   position: absolute;
}
</style>

</head>
<body>

<div id="boneco" style="left: 300px; top: 300px;"></div>

<script type="text/javascript">

var anima = function (id) {

   // obter elemento
   var el = document.getElementById(id);

   // obter posição inicial
   var posx = parseInt(el.style['left']);
   var posy = parseInt(el.style['top']);

   // definir maximos, minimos e pausa entre posições
   var minx = -6;
   var maxx = 6;
   var x = minx;
   var pausa = 100;

   // inicia animação
   var timer = setInterval(function () {

       // parar no maximo x
       if (x >= maxx) clearInterval(timer);

       // calcular y
       y = -1.3 * Math.pow(x, 2);

       // atualizar posição do elemento
       posx = posx + x;
       posy = posy + y;
       el.style['top'] = posy+'px';
       el.style['left'] = posx+'px';

       // incrementar x
       x++;

   }, pausa);

}

anima('boneco');

</script>

</body>
</html>

Edited by taviroquai

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.