V
V
virtualhero2015-03-23 11:50:32
JavaScript
virtualhero, 2015-03-23 11:50:32

How to describe a random fall trajectory in js?

Hello! After studying the js tutorial, I'm trying to write different programs. I want to write a program for a girl, similar to this codepen.io/radum/pen/xICAB , but instead of canvas I want to use animation and a lot of spans, with heart image styles. (Heart-fall =)))). I tried in different ways, did position: absolute for each span and experimented with span.style.left(top) + Math.random() in animation, etc. In general, it turned out not at all what I wanted. I tried to implement something similar through the coordinates, I still got confused. Help please at least approximately how to approach this, only without canvas'a. Please help, I really need to understand this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Deodatuss, 2015-03-23
@Deodatuss

I see it this way: hearts are generated with a random starting position (y:0;x:Math.random()*$(window).innerWidth()) . Then, for each heart, a random vector vector(x: (Math.random()*5)-10;y:Math.random()*5) is generated and written to its data attribute. Then we set setInterval and for each heart we add the value of the vector to its current position:

setInterval(function(){
   $('.heart').each(function(){
    $(this).css({top:$(this).offset().top+$(this).data('vector-y'),left:$(this).offset().left+$(this).data('vector-x')});
});
},50);

This will make the hearts fly in random directions. You can also add a sinusoid to the trajectory or any function you like to get rid of the linearity of the flight.
ps: I would do that. this may turn out to be a hell of a redneck code
UPDATE:
break me to do it on a clean one, read what each function does and implement it on a clean one if you want. Here is a more or less working example .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question