简体   繁体   English

如何制作SVG动画 <animate> 滚动标签

[英]How to animate SVG <animate> tag on Scroll

How can I make the svg's tag starts to works only when it is viewable by the screen. 我该如何使svg的标签仅在屏幕上可见时才开始起作用。 Here is a practice shortcode that I am working on 这是我正在努力的练习简码

<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>

The svg currently animates when the page loads. svg当前在页面加载时进行动画处理。 what I want is to make it work only when it is viewable on the screen. 我要使它仅在屏幕上可见时才起作用。

You can set begin="indefinite" to suppress an automatic start of the animation. 您可以设置begin="indefinite"以禁止动画的自动开始。 Then, in Javascript, you can use the .beginElement() method to start the animation at a time of your choosing. 然后,在Javascript中,您可以使用.beginElement()方法在您选择的时间启动动画。

Here is a basic example that takes the window's scroll event and tests whether the rectangle is in the viewport and then starts the animation (only once: restart="never" ). 这是一个基本示例,该示例接受窗口的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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM