html - 如何在 Scroll 上为 SVG <animate> 标签设置动画

标签 html css animation svg svg-animate

如何让 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/

相关文章:

html - 在 Web 检查器中找不到元素

javascript - 如何隐藏容器内 div 的短部分但显示另一个溢出部分

javascript - html5视频: play/pause custom button issue

带有箭头的 jQuery 切换下拉菜单

html - 使用 html5 和/或 CSS3 动画文本移动

javascript - Custom Tailoring 的 3D Web Application 是如何编写的?

html - 具有不同高度 block 的三列布局

jquery - 天际线后面的光线到天空,html5,css3(可能是动画)

javascript - 从 Paperscript 到 Javascript

javascript - 将 Popmotion 示例转换为 GreenSock