I've been playing around with JS+CSS animations for the first time. I am trying to rotate a div (or a bunch of them independently) with these random factors:
I managed to gather this script , which worked well. It rotates a div with id="square" infinity, into a [random] direction, by [random] degrees
function redo() {
$.fn.animateRotate = function(angle, duration, easing, complete) {
return this.each(function() {
var $elem = $(this);
$({deg: 0}).animate({deg: angle}, {
duration: duration,
easing: easing,
step: function(now) {
$elem.css({
transform: 'rotate(' + now + 'deg)'
});
},
complete: complete //|| $.noop
});
});
};
plusOrMinus = Math.random() < 0.5 ? -1 : 1;
randAngle = Math.floor(Math.random()*70+30) * plusOrMinus;
randDelay = Math.floor(Math.random()*3000+2000);
$('#square').animateRotate(randAngle);
timer = setTimeout(function() { redo(); },randDelay);
}
redo();
Now I've been having a few difficulties:
swing
or linear
, nor any other options such as duration
and complete
Solved.
I used a slightly different script but it now works. I added Transition and Animation lines to the CSS of the rotating element,
transition:2s;
animation:ease-in-out;
Those seemed to have fixed the issue for the jagged spinning, and let me add some easing. Then I used a wrapping function to pass different elements through the function.
<Script>
function rotate (elementID) {
var $rota = $(elementID),
degree = 0,
timer;
function spin() {
$rota.css({ transform: 'rotate(' + degree + 'deg)'}); // rotate element
plusOrMinus = Math.random() < 0.5 ? -1 : 1; // random spin direction
randAngle = Math.floor(Math.random()*70+50) * plusOrMinus; // random degrees
randDelay = Math.floor(Math.random()*1000+2000); //random delay
timer = setTimeout(function() { // set delay
degree += randAngle; // add random degree to current variable
spin(); // loop it
},randDelay);
}
spin(); // start first spin for element
};
rotate ('#square'); // run it
rotate ('#square2'); // run it again
</script>
Here it is at work http://jsfiddle.net/NWLVY/2/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.