增加和减少SVG形状-JS

时间:2019-03-01 22:30:30

标签: javascript html function svg

我希望您能在这里帮助我完成某项事情,以使SVG形状达到极限时先增大然后减小的函数。

它应该从3变为6,然后从6变为3,依此类推...但是相反,它应该从3变为6,然后从6变为负无穷大。而且我不明白为什么。

这是我的代码:

var size = 3;
var sizeManager = 1;

function increaseAnimation(el){

var elem = document.getElementById(el);

  elem.style.transform = "scale("+size+")";
  timer = setTimeout('increaseAnimation(\''+el+'\',3000)');
  size=size+0.005*sizeManager;

  if(size >= 6){
    sizeManager=sizeManager*-1;
  }

  if (size <= 3){
    sizeManager=sizeManager*+1;
  }
}

3 个答案:

答案 0 :(得分:2)

您的怪异的setTimeout实现,绑定已中断。 还有一个问题是您的sizeManager无法正确反映:

function increaseAnimation(id, interval) {
    var size = 1;
    var velocity = 0.05;
    var elem = document.getElementById(id);


    function iterate() {
        elem.style.transform = "scale(" + size + ")";

        size += velocity;

        if (size > 2 || size < 1) {
            velocity *= -1; // velocity reflected
        }
    }

    var timer = setInterval(iterate, interval);
    return function stop() {
        clearInterval(timer)
    }
}

我还添加了一个停止功能,以后可以调用该功能。

var stopper = increaseAnimation("content", 16);
setTimeout(stopper, 5000);

答案 1 :(得分:1)

错误发生在行sizeManager=sizeManager*+1;上,将数字乘以1不会改变它。基本上,您希望在-1和+1之间切换sizeManager,并且可以通过乘以-1来进行操作,而不论当前是负数还是正数。

我已经测试了这段代码,它似乎可以工作:

var size = 3;
var sizeManager = 1;

function increaseAnimation(el) {

    var elem = document.getElementById(el);

    elem.style.transform = "scale(" + size + ")";
    timer = setTimeout("increaseAnimation('" + el + "', 3000)");
    size += 0.005 * sizeManager;

    if (size >= 6 || size <= 3) {
        sizeManager *= -1;
    }
}

答案 2 :(得分:0)

用于POC演示的完整HTML,网址为:https://pastebin.com/GW0Ncr9A

霍勒,如果您有任何疑问。

function Scaler(elementId, minScale, maxScale, deltaScale, direction, deltaMsecs) {
    var scale = (1 == direction)?minScale:maxScale;
    var timer = null;

    function incrementScale() {
        var s = scale + deltaScale*direction;
        if (s < minScale || s > maxScale) direction *= -1;
        return scale += deltaScale*direction;
    };
    function doScale(s) {
        document.getElementById(elementId).style.transform = 'scale(' + s + ')';
    };

    this.getDeltaMsecs = function() {return deltaMsecs;};
    this.setTimer = function(t) {timer = t;};

    this.run = function() {doScale(incrementScale());};
    this.stop = function() {
        clearInterval(timer);
        this.setTimer(null);
    };
};

var scaler = new Scaler('avatar', 3, 6, .05, 1, 50);

function toggleScaler(ref) {
    if ('run scaler' == ref.value) {
        ref.value = 'stop scaler';
        scaler.setTimer(setInterval('scaler.run()', scaler.getDeltaMsecs()));
    }
    else {
        scaler.stop();
        ref.value = 'run scaler';
    }
};