【问题标题】:SVG.js, calling animate() in a loop doesn't workSVG.js,在循环中调用 animate() 不起作用
【发布时间】:2020-03-05 18:24:27
【问题描述】:

我正在使用 SVG.js 创建多个对象,然后同时为它们设置动画。我似乎无法使这项工作循环进行。如果我不使用循环,它工作正常。请参阅https://jsfiddle.net/drs44/5g8aextL/18/ 或下面的代码。我相信这与闭包作用域的工作方式有关。

var draw = SVG('drawing').size(450,450)
a = []

for (i= 0; i< 3; i++) {
a[i] = draw.rect(50, 50).move(65, 65).fill('#f06');
}

r2 = Math.random();
// This works:
a[0].animate(1000, '<>').during(function(pos, morph, eased){
    a[0].center(55 * eased + 95 * r2, 55 * eased + 105);});

a[1].animate(1000, '<>').during(function(pos, morph, eased){
    a[1].center(55 * eased + 85 * r2, 55 * eased + 125);});

a[2].animate(2000, '<>').during(function(pos, morph, eased){
    a[2].center(55 * eased + 75 * r2, 95 * eased + 45);});


/* But this doesn't work,  "Cannot read property 'center' of undefined'"
for (j=0; j<3; j++) {
    a[j].animate(2000, '<>').during(function(pos, morph, eased){
      a[j].center(55 * eased + 75 * r2, 95 * eased + 45);});
}
*/ 

【问题讨论】:

    标签: svg.js


    【解决方案1】:

    【讨论】:

    • 请将相关关键方面复制到您的答案中,以便在链接断开时该答案仍然有价值!
    【解决方案2】:

    似乎在同一位置生成重叠 svg 对象。

    var draw = SVG('drawing').size(450,450), a = [];
    
    var attrs = [{elapse: 1000, y: 95, x1: 55, x2: 105},
                        {elapse: 1000, y: 85, x1: 55, x2: 125},
                        {elapse: 2000, y: 75, x1: 95, x2: 45}];
    
    for (let i= 0; i< 3; i++) {
        let rect = draw.rect(50, 50).move(65, 65).fill('#f06');
        a.push(rect);
    }
    
    var r2 = Math.random(), j = 0;
    
    for (; j<3; j++) {
         a[j].animate(attrs[j].elapse, '<>').during(function(pos, morph, eased){
           a[j].center(55 * eased + attrs[j].y  * r2, attrs[j].x1 * eased + attrs[j].x2);});
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 2012-10-07
      • 2011-11-19
      相关资源
      最近更新 更多