首页 > 解决方案 > 如何为 SVG 制作动画滚动标签

问题描述

如何使 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 当前在页面加载时动画。我想要的是使其仅在屏幕上可见时才起作用。

标签: htmlcssanimationsvgsvg-animate

解决方案


您可以设置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>


推荐阅读