【问题标题】:How to animate SVG <animate> tag on Scroll如何在 Scroll 上为 SVG <animate> 标签设置动画
【发布时间】:2019-05-04 00:14:45
【问题描述】:
如何使 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 当前会显示动画。我想要的是使其仅在屏幕上可见时才起作用。
【问题讨论】:
标签:
html
css
animation
svg
svg-animate
【解决方案1】:
您可以设置begin="indefinite" 来禁止动画的自动启动。然后,在 Javascript 中,您可以使用 .beginElement() 方法在您选择的时间开始动画。
这是一个基本示例,它接受窗口的scroll 事件并测试矩形是否在视口中,然后启动动画(仅一次: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>