sinanisler logo

SVG Paths Animation with JavaScript

Javascript loop selects the class1, class2, classN… and animates them in circle. speed can be adjusted.

See the Pen Untitled by sinanisler (@sinanisler) on CodePen.

function animateDivsInCircle() {
    // Step 1: Get all elements by class name and their initial positions
    let elements = [];
    let initialPositions = [];

    for (let i = 1; i <= 19; i++) {
        let el = document.getElementsByClassName(`class${i}`);
        for (let j = 0; j < el.length; j++) {
            elements.push(el[j]);
            let rect = el[j].getBoundingClientRect();
            initialPositions.push({
                x: rect.left + rect.width / 2,
                y: rect.top + rect.height / 2
            });
        }
    }

    // Step 2: Animate elements in a circle relative to their initial positions
    let angle = 0;
    const radius = 50; // Adjust radius as needed
    const speed = 0.02; // Adjust for faster or slower animation

    function animate() {
        for (let i = 0; i < elements.length; i++) {
            let currentAngle = angle + (2 * Math.PI / elements.length) * i;
            let x = initialPositions[i].x + radius * Math.cos(currentAngle) - initialPositions[i].x;
            let y = initialPositions[i].y + radius * Math.sin(currentAngle) - initialPositions[i].y;
            elements[i].style.transform = `translate(${x}px, ${y}px)`;
        }
        angle += speed;
        requestAnimationFrame(animate);
    }

    animate();
}

// Call the function after DOM has loaded
document.addEventListener("DOMContentLoaded", animateDivsInCircle);

Leave the first comment