SVG progress circle with percentage

2019-02-07 20:04发布

问题:

im using the code found here to create a progress circle: http://codepen.io/JMChristensen/pen/Ablch

But i dont want it to be that big so i changed the circle radius for the inner and outer circle to be 40 instead of 90. Problem is after i do that the circle displaying the percentage stops working, no matter what percentage i type in the circle doesnt change and always appears to be at 100%.

here's the html:

<h1>SVG Circle Progress</h1>
<h2>Based off of CSS3 circle progress bars</h2>

    <div id="cont" data-pct="100">
    <svg id="svg" width="200" height="200" viewPort="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">
      <circle r="40" cx="100" cy="100" fill="transparent" stroke-dasharray="565.48" stroke-dashoffset="0"></circle>
      <circle id="bar" r="40" cx="100" cy="100" fill="transparent" stroke-dasharray="565.48" stroke-dashoffset="0"></circle>
    </svg>
    </div>
    <label for="percent">Type a percent!</label>
    <input id="percent" name="percent">

i think it has something to do with the stroke-dashoffset calculated in the js but i cant really figure out the math behind it.

回答1:

The animation in this progress meter is done using the SVG dash-array trick described in this article at css-tricks.com.

It works by defining a dashed line pattern for the circles used in the progress meter, where the length of the dash is equal to the path length of the stroked line in the SVG.

Since you changed the radius from 90 to 40, you need to scale the dash-array parameter from 2*pi*90 (565.48) to 2*pi*40 (251.33).

Here's an updated codepen



回答2:

The stroke-dasharray value needs changing as the radius changes.

Note that 565.48 = 2 * PI * 90 so when you change the radius you need to change the stroke-dasharray attribute to be 2 * PI * r where r is the new radius.



回答3:

Also you can set radius, dasharray and dashoffset with percentages. And it will be no need to dashoffset value recalculation.