|
| 1 | +import { Rive, Fit, Alignment, Layout, RuntimeLoader } from "@rive-app/canvas"; |
| 2 | + |
| 3 | +// Self-host the WASM backing dependency so we don't rely on a third-party CDN |
| 4 | +// at runtime and stay within the site's CSP (connect-src 'self') |
| 5 | +RuntimeLoader.setWasmUrl("/static/js/modules/rive/rive.wasm"); |
| 6 | + |
| 7 | +function initCareerProgressionAnimation() { |
| 8 | + const canvas = document.getElementById("rive-career-progression"); |
| 9 | + |
| 10 | + if (!canvas) { |
| 11 | + return; |
| 12 | + } |
| 13 | + |
| 14 | + const rivSrc = canvas.dataset.rivSrc; |
| 15 | + |
| 16 | + if (!rivSrc) { |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + const prefersReducedMotion = window.matchMedia( |
| 21 | + "(prefers-reduced-motion: reduce)" |
| 22 | + ).matches; |
| 23 | + |
| 24 | + // Track async state: the Rive WASM load and the scroll intersection can |
| 25 | + // complete in either order, so we reconcile them with flags. |
| 26 | + let hasLoaded = false; |
| 27 | + let isInView = false; |
| 28 | + |
| 29 | + const riveInstance = new Rive({ |
| 30 | + src: rivSrc, |
| 31 | + canvas: canvas, |
| 32 | + |
| 33 | + autoplay: !prefersReducedMotion, |
| 34 | + stateMachines: "State Machine 1", |
| 35 | + layout: new Layout({ fit: Fit.Cover, alignment: Alignment.Center }), |
| 36 | + onLoad: () => { |
| 37 | + riveInstance.resizeDrawingSurfaceToCanvas(); |
| 38 | + hasLoaded = true; |
| 39 | + // If the canvas is already off-screen when onLoad fires, pause now. |
| 40 | + if (!isInView && !prefersReducedMotion) { |
| 41 | + riveInstance.pause(); |
| 42 | + } |
| 43 | + }, |
| 44 | + }); |
| 45 | + |
| 46 | + // Only play the animation when the canvas is in view |
| 47 | + if (!prefersReducedMotion) { |
| 48 | + const observer = new IntersectionObserver( |
| 49 | + (entries) => { |
| 50 | + entries.forEach((entry) => { |
| 51 | + isInView = entry.isIntersecting; |
| 52 | + if (!hasLoaded) { |
| 53 | + return; |
| 54 | + } |
| 55 | + if (isInView) { |
| 56 | + riveInstance.play("State Machine 1"); |
| 57 | + } else { |
| 58 | + riveInstance.pause(); |
| 59 | + } |
| 60 | + }); |
| 61 | + }, |
| 62 | + { threshold: 0.1 } |
| 63 | + ); |
| 64 | + |
| 65 | + observer.observe(canvas); |
| 66 | + } |
| 67 | + |
| 68 | + window.addEventListener("resize", () => { |
| 69 | + riveInstance.resizeDrawingSurfaceToCanvas(); |
| 70 | + }); |
| 71 | +} |
| 72 | + |
| 73 | +if (document.readyState !== "loading") { |
| 74 | + initCareerProgressionAnimation(); |
| 75 | +} else { |
| 76 | + document.addEventListener("DOMContentLoaded", initCareerProgressionAnimation); |
| 77 | +} |
0 commit comments