问题描述:

This is a simple animation in the JavaScript library of Raphaël JS.

The function draws a field, then puts out the object of a pink rectangle.

When you hit the "gray" button the pink rectangle starts to move horizontally. The pink rectangle moves and once it hits its destined position it stops.

What I need help with is:

1: Make the pink rectangle return to its starting position.

2: Loop the animation so the pink rectangle goes back and forth.

I have tried to solve this by adding "x: 0", after the "x:-1" but without success. As you can see I've also set the repeat to infinity, also without success.

The field:

var p = Raphael(0, 0, 240, 140);

p.rect(0,0,240,70);

The trigger button and function from onclick:

p.rect(130, 80, 50, 25)

.attr({

fill : "grey",

"stroke-width" : 1

})

.click(function(){

pinkRect.animate({

repeat: "Infinity",

x:-1,

}, 2000);

});

网友答案:

You need to use the callback function of the animate method, and make it call itself, as you effectively have 2 animations. So the key bit is the 2nd bit below...

p.rect(130, 80, 50, 25)
    .attr({
        fill : "grey",
        "stroke-width" : 1
    })
    .click( animPink );

function animPink() {
    var x = pinkRect.attr('x') < 0 ? 150 : -1;
    pinkRect.animate({ x: x }, 2000, animPink);
};

jsfiddle click 3rd grey box

相关阅读:
Top