[英]How to gradually change attribute values with Javascript? eg. Ease-in, Ease-out
我想將元素的屬性(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>
您可以嘗試使用簡單的數字遞增器/遞減器,如下所示:
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.