javascript 带百分比的 SVG 进度圈
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26781576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SVG progress circle with percentage
提问by user3840848
im using the code found here to create a progress circle: http://codepen.io/JMChristensen/pen/Ablch
我使用这里找到的代码来创建一个进度圈: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%.
但我不希望它那么大,所以我将内圆和外圆的圆半径改为 40 而不是 90。问题是在我这样做之后,显示百分比的圆圈停止工作,无论我在圆圈不会改变,并且始终显示为 100%。
here's the html:
这是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.
我认为这与在 js 中计算的 stroke-dashoffset 有关,但我无法真正弄清楚它背后的数学原理。
回答by r3mainer
The animation in this progress meter is done using the SVG dash-array trick described in this article at css-tricks.com.
此进度表中的动画是使用css-tricks.com 上的这篇文章中描述的 SVG dash-array 技巧完成的。
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.
它的工作原理是为进度表中使用的圆圈定义虚线图案,其中虚线的长度等于 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).
由于您将半径从 90 更改为 40,因此您需要将dash-array
参数从 2*pi*90 (565.48) 缩放到 2*pi*40 (251.33)。
回答by Robert Longson
The stroke-dasharray value needs changing as the radius changes.
stroke-dasharray 值需要随着半径的变化而变化。
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.
请注意,565.48 = 2 * PI * 90
当您更改半径时,您需要将 stroke-dasharray 属性更改为 2 * PI * r,其中 r 是新半径。
回答by Alex Vauch
Also you can set radius, dasharray and dashoffset with percentages. And it will be no need to dashoffset value recalculation.
您还可以使用百分比设置半径、dasharray 和 dashoffset。并且不需要重新计算 dashoffset 值。