Single metric animated SVG pie chart

In this example below you will see how to do a Single metric animated SVG pie 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>Single metric animated SVG pie chart</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <svg width="200px" height="200px" viewPort="0 0 200 200">
  <defs>
    <clipPath id="clip">
      <circle cx="100" cy="100" r="100"></circle>
    </clipPath>
  </defs>
  <circle class="progress" cx="100" cy="100" r="100" clip-path="url(#clip)"></circle>
</svg>
<br>
<br>
<br>
<button>Set</button>
  
  

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




</body>

</html>

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

.progress {
  fill: #666;
  stroke: #000;
  transform-origin: center;
  transform: rotate(-90deg);
}

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

/*Downloaded from https://www.codeseek.co/13twelve/single-metric-animated-svg-pie-chart-RyzLLy */
function setCircle(percent,setup) {
  let $svg = document.querySelector('svg');
  let $progress = document.querySelector('.progress'); // is black to show %
  let radius = $progress.getAttribute('r');
  let circumference = 2 * Math.PI * radius;
  let progress = (percent/100) * circumference;
  
  if (!setup) {
    $svg.classList.add('s-ready');
  } else {
    $progress.style.strokeWidth = 2 * radius + 'px';
  }
  
  // draw the top the correct size
  $progress.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