circles-animation

js animated svg circles

by Alexandru Gatea

HTML

<div id="svgCircles"></div>

SCSS

/* variables */
$cw: 300px;
// styles
* {
    margin: 0;
    padding: 0;
}

body {
    background: #212121;
}

#svgCircles {
    animation: rotate 3s linear infinite;
}

@function pi() {
    @return 3.14159265359;
}

@for $i from 1 through 20 {
    $radius: $i * 15;
    $circleLength: 2 * $radius * pi();
    $halfCircle: $circleLength / 2;
    $duration: 2 +  $i * 0.25;
    @keyframes growStroke-#{$i} {
        0% {
            stroke-dasharray: #{$circleLength};
            stroke-dashoffset: -#{$halfCircle};
        }
        100% {
            stroke-dasharray: 0;
            stroke-dashoffset: 0;
        }
    }
    .circle-#{$radius} {
        animation: growStroke-#{$i} #{$duration}s  infinite linear alternate;
    }
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(720deg);
    }
}


.circle {
  &.circle-15{stroke: #29B6F6!important;}
  &.circle-30{stroke: #29B6F6!important;}
  &.circle-45{stroke: #0288D1!important;}
  &.circle-60{stroke: #0288D1!important;}
  &.circle-75{stroke: #039BE5!important;}
  &.circle-90{stroke: #039BE5!important;}
  &.circle-105{stroke: #03A9F4!important;}
  &.circle-120{stroke: #03A9F4!important;}
  &.circle-135{stroke: #29B6F6!important;}
  &.circle-150{stroke: #29B6F6!important;}
}

.circle {
  stroke: #fff!important;
}

JavaScript

jQuery(document).ready(function($) {

  // set width and height of svg
  var svgDim = 400;

  // get container element
  var circles = $("#svgCircles").css({
    width: svgDim + "px",
    height: svgDim + "px",
    marginLeft: -(svgDim / 2) + "px",
    marginTop: -(svgDim / 2) + "px",
    position: 'fixed',
    top: '50%',
    left: '50%'
  });

  // calculate svg center position
  var center = svgDim / 2;
  var circle;

  // generate svg element
  var svg = $('<svg width="' + svgDim + '" height="' + svgDim + '"></svg>');

  // generate circles
  for (var i = 1; i < 11; i++) {
    //set element grow rate
    var el = i * 15;

    circle = $('<g><circle class="circle circle-' + el + '" cx="' + center + '" cy="' + center + '" r="' + el + '" stroke="#CDDC39" stroke-width="7" fill="transparent"></circle></g>');
    svg.append(circle);
  }

  // append circles inside parent container
  circles.append(svg);
  
  //svg's are attached to DOM but will not be fisible without a refresh
  $("#svgCircles").html($("#svgCircles").html());
})