我想将元素的属性(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。我希望它逐渐增加和减少呼吸类型的效果。
最佳答案
如果您打算使用 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>
否则,使用 <animate>
, 你需要使用它的 values
和 keyTimes
属性:
#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>
关于javascript - 如何使用 Javascript 逐渐更改属性值?例如。缓入缓出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669397/