bbarriatos
bbarriatos

Reputation: 57

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. 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. what I want is to make it work only when it is viewable on the screen.

Upvotes: 1

Views: 293

Answers (1)

ccprog
ccprog

Reputation: 21811

You can set begin="indefinite" to suppress an automatic start of the animation. Then, in Javascript, you can use the .beginElement() method to start the animation at a time of your choosing.

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").

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>

Upvotes: 1

Related Questions