Animated SVG circle chart

In this example below you will see how to do a Animated SVG circle chart with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 13twelve, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 13twelve ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Animated SVG circle chart</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  
<svg width="200px" height="200px" viewPort="0 0 200 200">
    <circle class="background" cx="100" cy="100" r="65"></circle>
    <circle class="progress-bottom" cx="100" cy="100" r="80"></circle>
  <circle class="progress-top" cx="100" cy="100" r="80"></circle>
</svg>

<br>
<br>
<br>
<button>Set</button>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/13twelve/animated-svg-circle-chart-pVmMjK */
svg {
  margin-top: 40px;
  margin-left: 40px;
}

circle {
  fill: none;
  transform-origin: center;
  transform: rotate(-90deg);
}

.background {
  stroke: #ccc;
  stroke-width: 2px;
}

.progress-bottom {
  opacity: 0;
  stroke: #fff;
  stroke-width: 32px;
}

.progress-top {
  opacity: 0;
  stroke: #000;
  stroke-width: 30px;
}

.s-ready .progress-top,
.s-ready .progress-bottom {
  opacity: 1;
  transition: stroke-dasharray .5s cubic-bezier(.5, -.3, .5, 1.3);
}

/*Downloaded from https://www.codeseek.co/13twelve/animated-svg-circle-chart-pVmMjK */
function setCircle(percent,setup) {
  let svg = document.querySelector('svg');
  let bottom = document.querySelector('.progress-bottom'); // is white to mask the grey base
  let top = document.querySelector('.progress-top'); // is black to show %
  let radius = top.getAttribute('r');
  let circumference = 2 * Math.PI * radius;
  let progress = (percent/100) * circumference;
  let bottomOffset = 30; // we want 15px either side of the main line as a stroke around the top, we can't put a stroke on a stroke
  
  if (!setup) {
    svg.classList.add('s-ready');
  } else {
    // offsetDegrees begins at -90 so the circle starts top middle
    // because we want 15px either side, we need to rotate the bottom around a little
    // so we need to convert -15px to degrees
    let offsetDegrees = 0 - 90 - (((bottomOffset/circumference) * 360) * 0.5);
    bottom.style.transform = 'rotate(' + offsetDegrees + 'deg)';
  }
  
  // draw the bottom 8px too big
  bottom.setAttribute('stroke-dasharray',(progress + bottomOffset)+','+circumference);
  // draw the top the correct size
  top.setAttribute('stroke-dasharray',progress+','+circumference);
}

setCircle(0,true);

document.querySelector('button').addEventListener("click", function(){
  let num = Math.floor(Math.random() * 100) + 1;
  setCircle(num);
}, false);

Comments