Animating SVG elements with GSAP

时间:2016-04-25 08:49:15

标签: javascript animation dom svg gsap

I am tasked with creating an interactive SVG infographic with few slides for a browser game, it has 5 steps total. When you click prev / next buttons or a specific step, the whole svg should animate itself to the correct step.

In terms of code, this is what I have:

function Slide() {

    // Cache all top-level svg elements for later use
    this.el = $('svg#betfair-slider');
    this.hands = this.el.find('#hands_8_');
    this.cardsDesk = this.el.find('g#center-cards');
    this.textContainer = $('.step-text');

    // Use a shared timeline across all slides, so there are no overlapping tweens
    this.tween = new TimelineLite();
}

function Slide2 () {

    // Inherit from the main slide
    Slide.call(this);

    // each slide has its own supporting explanatory text
    this.html = [
        '<h3>Preflop</h3>',
        '<p>Amet sit lorem ipsum dolar</p>'
    ].join('');

    // the main openslide method
    this.openSlide = function() {
        // find the cards that need to be animated for this specific slide
        var cards = this.hands.find('.card');
        // fade out each card
        this.tween.staggerTo(cards, 0.2, { opacity: 0 }, 0.2);
        // Render supporting text
        this.textContainer.html(this.html);
    };

}

Here are the cards I am trying to get: enter image description here

I am able to fetch them using the this.hands.find('.card'); jquery method (I can see them in the console), but I just can't animate them. I have tried animating different attributes (opacity, x, y, left, etc), but nothing happens - nothing moves on the screen.

I am able to do this.hands.find('.card').hide() and change the css using jQuery, but why TimelineLite doesn't work here? I also tried this approach:

var cards = this.hands.find('.card');
for (var i = cards.length - 1; i >= 0; i -= 1) {
    var card = cards[i];
    this.tween.to(card, 0.2, { opacity: 0 });
}

But still no success... The interesting thing is that when I attach an onComplete callback on the tweens, THEY ARE fired, but absolutely nothing moves on the screen. You can check out everything here.

Thanks for the help in advance, any suggestions are more then welcome.

1 个答案:

答案 0 :(得分:1)

我认为你可能误解了时间表的运作方式(或者我误解了你的意图)。与所有补间一样,默认情况下,时间轴立即开始播放。因此,如果您正在使用一个时间轴并根据用户交互推送所有补间(意味着在您创建它和填充它之间的时间过去......并填充更多...),它的播放头已经有了高级。我打赌这会导致你的补间几乎立刻跳到他们的最终状态。这不是一个错误 - 事情应该如何运作,尽管GSAP中有一些逻辑可以在某些情况下调整行为以使其更直观。

我看到了几个选项:

  1. 只需使用TweenMax而不是TimelineLite。像TweenMax.staggerTo(...)和TweenMax.to(...)。
  2. 或者只为每个用户交互创建一个TimelineLite(而不是全局的所有补间中的一个)。这样你就可以马上填充它,它会按照你的预期播放。
  3. 如果您真的想要,可以使用一个全局时间轴,但如果要在每个用户交互上插入补间而不是一次性插入补间,则可能只需要管理其播放头。

    如果您仍然遇到问题,请不要犹豫,在http://greensock.com/forums/的GSAP专用论坛上发帖,如果您包含一个codepen或jsfiddle简化测试用例,那么这将非常有用,这样我们就可以修补很快就能看到发生了什么以及这些变化如何影响结果。

    快乐的补间!