简体   繁体   中英

Javascript animation only loading once per page

I have an SVG, animated wavy line. I'd like these wavy lines to appear multiple times on a certain page. However, only the first instance seems to show and the others don't... I know this because if I delete the first one in the inspector, the next one displays.

Here's my code:

 let xs = [] for (var i = 0; i <= 200; i++) { xs.push(i) } let t = 0 function animatewavy() { let points = xs.map(x => { let y = 10 + 2 * Math.sin((x + t) / 5) return [x, y] }) let path = "M" + points.map(p => { return p[0] + "," + p[1] }).join(" L") document.querySelector("path").setAttribute("d", path) t += 0.8 requestAnimationFrame(animatewavy) } animatewavy()
 .wavy-line { margin:35px auto; width:150px; }.wavy-line svg { height: 15px; width:150px; }.wavy-line path { stroke-width: 5px; fill: none; }.wavy-line.path-green { stroke: #56AE5F; }.wavy-line.path-blue { stroke: #1FB5D1; }.wavy-line.path-yellow { stroke: #F9B930; }
 <div class="wavy-line"><svg><path class="path-blue"></path></svg></div> <div class="wavy-line"><svg><path class="path-blue"></path></svg></div> <div class="wavy-line"><svg><path class="path-blue"></path></svg></div> <div class="wavy-line"><svg><path class="path-blue"></path></svg></div>

You'll see the first one appearing but the rest of them not... Im not sure what im doing wrong, do I need to somehow end the javascript and restart it?

I'd appreciate any help possible:)

change the document.querySelector() to the document.querySelectorAll()

or

better still u can iterate the containers to fix ur animations in.

document.querySelector("path") returns only the first match, that's why only the first svg is animating.

To animate all svg's at once, get all path nodes as an array using document.querySelectorAll and iterate over them to call setAttribute on each one like so:

document.querySelectorAll("path").forEach(elem => elem.setAttribute("d", path))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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