【问题标题】:How to gradually change attribute values with Javascript? eg. Ease-in, Ease-out如何使用 Javascript 逐渐改变属性值?例如。缓入缓出
【发布时间】:2020-04-27 09:05:33
【问题描述】:

我想将元素的属性(SVG 的过滤器)从 0 更改为 10,然后无限更改为 0。为此我做了一个js函数呼吸:

let flag = 0;
let loader = setInterval(breathe, 1000);

function breathe() {
  if (flag === 0) {
    document
      .getElementById("main-blur")
      .setAttribute("stdDeviation", "10");
    flag = 1;
    return;
  } else {
    document
      .getElementById("main-blur")
      .setAttribute("stdDeviation", "0");
    flag = 0;
    return;
  }
}

问题是模糊值直接从10变为0。我希望它逐渐增加和减少以获得呼吸类型的效果。

【问题讨论】:

标签: javascript html css


【解决方案1】:

如果您要使用 JS 解决方案而不是使用<animate>,则应使用window.requestAnimationFrame()

// Get a reference to the SVG filter only once:
const gaussianBlur =  document.getElementById('gaussianBlur');

// To control the animation: 0 to 100 we increase blur, 100 to 200 we decrease blur. We use these
// values instead of 0-10 and then divide by 10 to produce a smoother animation.
let step = 0;

function tick() {
  const blur = step < 100 ? step : 200 - step;

  // Update blur (converting step to 0-10). You could change this to take into account time:
  gaussianBlur.setAttribute('stdDeviation', blur / 10);

  // Update step:
  step = (step + 1) % 200;
  
  requestAnimationFrame(tick);
}

tick();
#element {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  transform: translate(-50%, -50%);
}
<svg id="element" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <filter id="blurFilter" x="-100%" y="-100%" width="300%" height="300%">
    <feGaussianBlur id="gaussianBlur" />
  </filter>
  
  <circle cx="50" cy="50" r="25" style="filter: url(#blurFilter); " />
</svg>

否则,使用&lt;animate&gt;,你需要使用它的valueskeyTimes属性:

#element {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  transform: translate(-50%, -50%);
}
<svg id="element" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <filter id="blurFilter" x="-100%" y="-100%" width="300%" height="300%">
    <feGaussianBlur id="gaussianBlur" stdDeviation="1" />
  </filter>
  
  <animate
    xlink:href="#gaussianBlur"
    attributeName="stdDeviation"
    dur="2s"
    repeatCount="indefinite"
    values="0; 10; 0"
    keyTimes="0; .5; 1"
  />
  
  <circle cx="50" cy="50" r="25" style="filter: url(#blurFilter); " />
</svg>

【讨论】:

    【解决方案2】:

    您可以尝试使用简单的数字增量器/减量器,如下所示:

    let delta = 1;
    let current = 0;
    let loader = setInterval(breathe, 1000);
    function breathe() {
    
        if (current === 10) delta = -1;
        else if (current === 0) delta = 1;
        current += delta;
        document.getElementById("main-blur")
            .setAttribute("stdDeviation", String(current));
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-24
      • 2013-01-20
      • 2010-12-17
      • 2010-12-05
      • 2020-10-15
      • 1970-01-01
      相关资源
      最近更新 更多