我想无限地将元素的属性(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。我希望它逐渐增加和减少,以达到呼吸类型的效果。
发布于 2020-01-10 02:40:14
如果您打算使用JS解决方案,而不是使用,则应该使用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>
发布于 2020-01-10 01:42:41
您可以尝试使用简单的数字递增/递减,如下所示:
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));
}https://stackoverflow.com/questions/59669397
复制相似问题