daugaard47
daugaard47

Reputation: 1868

Dynamic Radial progress bar

I'm working on a radial progress meter for a fundraiser and would like to keep track of the donations based on percentages.

I have everything working except the stroke fill is off. Example: I set the data-percentage to 75 and it renders around 55%. (The fill stroke starts to show at data-percent="38")

I need to to go from 0% - 100%

Could someone help me fix the calculation error?

HTML:

<div class="flex justify-center mt-10">
  <div class="w-1/2">
    <div class="svgbox">
      <div class="progressdiv" data-percent="38">
        <svg class="progress" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="50" fill="transparent" stroke-dasharray="502.4" stroke-dashoffset="0" ></circle>
  <circle class="bar" cx="50" cy="50" r="50" fill="transparent" stroke-dasharray="502.4" stroke-dashoffset="0"></circle>
        </svg>
        <img src="https://www.okayplayer.com/wp-content/uploads/2015/07/Barack-Obama-House-Music-Square.jpg" class="rounded-full absolute left-0 top-0" style="width: 92%;left: 50%; top:50%; transform: translate(-50% , -50%);">
      </div>
    </div>
  </div>
</div>

CSS:

body {
  background-color: #1e2d47;
}

.progress {
  display: block;
  margin: 0 auto;
  overflow: visible;
  transform: rotate(-90deg) rotateX(180deg);
}

.progress circle {
  stroke-dashoffset: 0;
  transition: stroke-dashoffset 1s ease;
  stroke: #f5f5f5;
  stroke-width: 2px;
}

.progress .bar {
  stroke: #d66f6f;
}

.progressdiv {
  position: relative;
}

.svgbox {
  height: 0;
  width: 100%;
  padding-top: (svg height / svg width) * width-value;
  position: relative;
}

JS:

(function() {
  window.onload = function() {
    var totalProgress, progress;
    const circles = document.querySelectorAll(".progress");
    for (var i = 0; i < circles.length; i++) {
      totalProgress = circles[i]
        .querySelector("circle")
        .getAttribute("stroke-dasharray");
      progress = circles[i].parentElement.getAttribute("data-percent");

      circles[i].querySelector(".bar").style["stroke-dashoffset"] =
        totalProgress * progress / 100;
    }
  };
})();

Codepen: https://codepen.io/daugaard47/pen/OGBbBK

Upvotes: 1

Views: 932

Answers (1)

crishpeen
crishpeen

Reputation: 148

You have wrong values of stroke-dasharray="" in your svg. Correct calculation should be 2*π*r. That mean in your case 2*π*50, which is something like 314.16.

Upvotes: 3

Related Questions