如何从以下原型创建动画工具

时间:2017-02-21 20:09:41

标签: javascript jquery css animation jquery-animate

我最近被问到这个问题:如何解决这个问题?创建一个允许设计人员配置动画的工具。为了实现这一点,请在JavaScript中实现可以渲染这些动画的AnimationSequence。

例如,如果设计师想要配置条形元素的填充,那么AnimationSequence的用法将如下所示

var barSequence = new AnimationSequence(bar, [
  [100, { width: '10%' }],
  [200, { width: '20%' }],
  [200, { width: '50%' }],
  [200, { width: '80%' }],
  [300, { width: '90%' }],
  [100, { width: '100%' }]
]);

barSequence.animate();

其中序列中每个步骤的第一个元素是步骤发生前的毫秒数,第二个元素是包含任意数量CSS属性的对象。

你将如何实现AnimationSequence?

1 个答案:

答案 0 :(得分:1)

您需要构建一个队列系统,然后根据第一个值调用每个动画帧。所以像这样......

var AnimationSequence = function(elem, opts) {
    this.element = (typeof elem == "object") ? elem : $(elem); //jQuery
    this.options = opts;
    this.queue = [];
    this.timer = 0;
    this.init(opts);
}
AnimationSequence.prototype = {
    init: function(opts) {
        var that = this;
        for(var i = 0, l = opts.length; i < l; i++) {
            this.queue.push({delay: opts[i][0], command: opts[i][1]});
        }
        this.deQueue();
    },
    deQueue: function() {
        if(this.queue.length) {
            var animation = this.queue.shift(),
                that = this;
            this.timer = setTimeout(function() {
                that.element.animate(animation.command, function() {
                that.deQueue();
                });
            }, animation.delay);
        }
    }
};
$(function() {
    var barSequence = new AnimationSequence(".bar", [
        [100, { width: '10%' }],
        [200, { width: '20%' }],
        [200, { width: '50%' }],
        [200, { width: '80%' }],
        [300, { width: '90%' }],
        [100, { width: '100%' }]
    ]);
});

显然你会得到html ......

<div id="bar-holder">
    <div class="bar"></div>
</div>

和Css ......

#bar-holder {
    width: 100%;
    padding: 5px;
    background: #ccc;
}
.bar {
    height: 25px;
    background: red;
}

工作jsfiddle示例...... https://jsfiddle.net/kprxcos4/ 显然你可能想要加强它,但这是一个可以处理参数和自定义字段的动画队列系统的开始。