Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

How can I make the animation start when the user gets to the section where the elements…

  1. User

    How can I make the animation start when the user gets to the section where the elements are?

  2. Assistant

    To start the animation only when the user scrolls to (or near) the section containing your charts, you can use the Intersection Observer API. It lets you detect when an element enters or leaves the viewport in an efficient way.

    Here’s how you can update your existing code:


    Step 1: Wrap your animation logic in a function

    Right now, it animates immediately on page load. Extract it into a function that gets called when the section becomes visible.

    Step 2: Use Intersection Observer to trigger the animation

    Observe the container holding all charts (.charts-wrapper). When it comes into view, run the animation.


    Updated code:

    <script>
    const charts = [
      { canvasId: 'chart1', percent: 40 },
      { canvasId: 'chart2', percent: 50 },
      { canvasId: 'chart3', percent: 100 },
    ];
    
    const radius = 40;
    const lineWidth = 20;
    const animationDuration = 2000;
    const fps = 60;
    
    // Function to animate all charts
    function animateCharts() {
      charts.forEach(({ canvasId, percent }) => {
        const canvas = document.getElementById(canvasId);
        const ctx = canvas.getContext('2d');
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        let currentPercent = 0;
        const increment = percent / (fps * (animationDuration / 1000));
    
        function drawDoughnut(p) {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
    
          // Background arc
          ctx.beginPath();
          ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
          ctx.lineWidth = lineWidth;
          ctx.strokeStyle = '#D9D9D9';
          ctx.lineCap = 'butt';
          ctx.stroke();
    
          // Foreground arc (progress)
          const startAngle = -Math.PI / 2;
          const endAngle = startAngle - (2 * Math.PI * (p / 100));
    
          ctx.beginPath();
          ctx.arc(centerX, centerY, radius, startAngle, endAngle, true);
          ctx.strokeStyle = '#2D5C9D';
          ctx.lineCap = 'butt';
          ctx.stroke();
        }
    
        function animate() {
          if (currentPercent < percent) {
            currentPercent += increment;
            if (currentPercent > percent) currentPercent = percent;
            drawDoughnut(currentPercent);
            requestAnimationFrame(animate);
          } else {
            drawDoughnut(percent);
          }
        }
    
        animate();
      });
    }
    
    // Intersection Observer to trigger animation
    const chartsWrapper = document.querySelector('.charts-wrapper');
    
    const observerOptions = {
      root: null, // viewport
      threshold: 0.3 // trigger when 30% of the wrapper is visible
    };
    
    function onIntersect(entries, observer) {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          animateCharts();
          observer.unobserve(entry.target); // Run only once
        }
      });
    }
    
    const observer = new IntersectionObserver(onIntersect, observerOptions);
    observer.observe(chartsWrapper);
    </script>
    

    Explanation:

    • You create a new observer that watches the .charts-wrapper div.
    • When at least 30% of it becomes visible (threshold: 0.3), the callback fires.
    • The callback triggers animateCharts() which runs your animations.
    • Unobserve immediately so it runs only once (prevents repeating when scrolling back).

    This approach is performant and works well on modern browsers.


    Let me know if you want me to help make this work with older browsers or want it to restart on scroll back!