Why won't my Raphael JS animation loop?

2019-02-13 02:26发布

Hi there I've made this animation using the Raphael framework. I want the star (logoStar) to spin indefinitely but it only runs once. Can anyone help? Thanks

window.onload = function () {
buildLogo();
}

var buildLogo = function () {
    var logo = Raphael("title",800,236);

    var logoStar = logo.path("M12.245 131.057L16.039 138.743L24.521 139.974L18.383 145.958L19.832 154.406L12.245 150.418L4.658 154.406L6.108 145.958L-0.03 139.974L8.452 138.743").attr({fill:"#fff",stroke:"none"});

    var starSpin = function () {
        logoStar.animate({rotation: "360"}, 5000, starSpin);
    }
    starSpin();
}

6条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-13 02:54

I agree with Michael Mao, you should put

logoStar.animate({rotation: "360"}, 5000, starSpin);

in a loop.

But loops like this while(true) are not always a good idea. It will take too much CPU and some browsers may warn the user that a script is causing the page to run slowly. Maybe it is best to add a timeout before re-executing animate. Just try and see what works best ;)

查看更多
Melony?
3楼-- · 2019-02-13 03:03

I'm not entirely sure, but I think that starSpin is not yet defined when you try to use it in the anonymous function.

Try changing:

var starSpin = function () {
    logoStar.animate({rotation: "360"}, 5000, starSpin);
}
starSpin();

to

function starSpin() {
    logoStar.animate({rotation: "360"}, 5000, starSpin);
}
starSpin();

EDIT
It turns out that that's not it at all -- I do not know what the problem is (hopefully someone who has more exposure to the Raphael library can help out there) but a kludgey-but-works solution is to clear the element in question before calling the entire construct function in the callback (I warned you it was kludgey).

SEE: http://jsfiddle.net/rbf5x/1/

查看更多
Root(大扎)
4楼-- · 2019-02-13 03:05

Just a quick observation:

Looks like "Rotation" isn't part of the Atrr anymore since ver 2, so you can't use it in "animate", but you can replace that with "transform: "r" + (some degree)"..

eg:

 element.animate( {transform: "r" + (-90)}, 2000, 'bounce');
查看更多
一夜七次
5楼-- · 2019-02-13 03:10

I am not very sure but what if you do this:

while(true){starSpin();}

It sounds like the method is only executed once, so it "spins" once...

查看更多
迷人小祖宗
6楼-- · 2019-02-13 03:11

Since version 2 came out, the real way to have an infinitely looping animation is this:

var spin = Raphael.animation({transform: "r360"}, 2500).repeat(Infinity);
myElement.animate(spin);

Infinity is a property in Javascript, so don't enter it as a string.

Here's a working fiddle.

查看更多
甜甜的少女心
7楼-- · 2019-02-13 03:18
var starSpin = function () {
    logoStar.attr({rotation: 0}).animate({rotation: 360}, 5000, starSpin);
}

Animation from 360° to 360° looks like there no animation, so you need to reset rotation to zero before.

查看更多
登录 后发表回答