如何让 svg 的标签仅在屏幕可见时才开始工作。这是我正在研究的一个练习简码
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="400" height="200" viewBox="0 0 400 200">
<g>
<rect x="50" y="0" fill="#f00" width="100" height="100">
<animate id="op1" attributeName="height" from="0" to="100" dur="0.5s" fill="freeze" />
</rect>
</g>
</svg>
svg 当前在页面加载时进行动画处理。我想要的是让它仅在屏幕上可见时才工作。
最佳答案
您可以设置 begin="indefinite"
来抑制动画的自动开始。然后,在 Javascript 中,您可以使用 .beginElement()
方法在您选择的时间启动动画。
这是一个基本示例,它获取窗口的 scroll
事件并测试矩形是否在视口(viewport)中,然后启动动画(仅一次:restart="never"
).
var op1 = document.querySelector('#op1');
var ticking = false;
// test if element is at least partial in viewport
function isElementVisible (el) {
var rect = el.getBoundingClientRect();
return (
rect.bottom >= 0 ||
rect.right >= 0 ||
rect.top <= window.innerHeight ||
rect.left <= window.innerWidth
);
}
window.addEventListener('scroll', function () {
// call only once per animation frame
if (!ticking) {
window.requestAnimationFrame(function() {
// the animated element is the parent of the animate element
if (isElementVisible(op1.parentElement)) {
op1.beginElement();
}
ticking = false;
});
ticking = true;
}
});
svg {
position:relative;
top: 300px;
}
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200" viewBox="0 0 400 200">
<rect x="50" y="0" fill="#f00" width="100" height="100">
<animate id="op1" attributeName="height" from="0" to="100"
begin="indefinite" dur="0.5s" fill="freeze" restart="never" />
</rect>
</svg>
关于html - 如何在 Scroll 上为 SVG <animate> 标签设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581270/