'SVG textPath animation on Scroll multiple times on a page
I’m trying to get multiple headings on a Shopify homepage to be animated on a svg textPath. My code loads the headings and they each sit on their own svg curved path. However, only one heading is animated on scroll. How do I get each of the headings to be animated on scroll? Do I need multiple window.addEventListener(‘scroll’, onScroll-n) functions for each heading?
<script>
console.clear();
var textPath = document.querySelector('#text-path');
var textContainer = document.querySelector('#text-container');
var path = document.querySelector( textPath.getAttribute('href') );
var pathLength = path.getTotalLength();
console.log(pathLength);
function updateTextPathOffset(offset){
textPath.setAttribute('startOffset', offset);
}
updateTextPathOffset(pathLength);
function onScroll(){
requestAnimationFrame(function(){
var rect = textContainer.getBoundingClientRect();
var scrollPercent = rect.y / window.innerHeight;
console.log(scrollPercent);
updateTextPathOffset( scrollPercent * 2 * pathLength );
});
}
window.addEventListener('scroll',onScroll);
</script>
<svg id="text-container" viewBox="0 0 1000 200" xmlns="http://www.w3.org/2000/svg">
<path id="text-curve" d="M0 100s269.931 86.612 520 0c250.069-86.612 480 0 480 0" fill="none"/>
<text y="40">
<textPath id="text-path" href="#text-curve" startOffset="200">
{{ section.settings.title }}
</textPath>
</text>
</svg>
Solution 1:[1]
You can do the align animation with SVG SMIL:
https://developer.mozilla.org/en-US/docs/Web/SVG/SVG_animation_with_SMIL
Set the values dynamically from your Scroll Event
<svg width="450" height="180">
<path id="P1" pathLength="200" d="M0 100s270 87 520 0c250-87 480 0 480 0" fill="none" stroke-width="2" stroke="red"/>
<text>
<textPath id="P2" href="#P1">
TEXT
<animate
attributeName="startOffset"
attributeType="XML"
values="0;80"
keyTimes= "0;1"
dur="2s"
fill="freeze"
repeatCount="1"/>
</textPath>
</text>
<animateMotion>
<mpath href="#P2" />
</animateMotion>
</svg>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
