javascript - 根据设置的百分比包围对象

标签 javascript html css svg loader

我有这样的任务:一个没有边框的圆,我们得到一些百分比(来自用户或只是我们自己输入 - 无关紧要),之后圆的边框应该根据这个数字填充。 我正在尝试使用 SVG。但我不清楚。它不适用于百分比,我不知道如何为所有长度获得正确的数字

<svg width="270" height="270">
  
    <circle 
            r="115" cx="135" cy="135"
            fill="none";
            stroke="blue"
            stroke-width="15"            
            stroke-dasharray="1000"
            stroke-dashoffset="0%">
    <animate 
            attributeName="stroke-dashoffset" 
            attributeType="CSS"
            from="1000" to="00"
            begin="0s" dur="2s"/>

</svg>

Image to see how it shoul be

最佳答案

一个观察:如果你希望它是完整的,那么Stroke-dasharray的值应该是圆的周长(以像素为单位)。所以2*Pi*r

笔划-dashoffset是从笔划偏移的像素量,例如:

半径为 115 像素的圆的周长为 2*Pi*115=722.56 723 像素。 如果我们想将其填充为 75%,则必须将笔画偏移 723*(1-0.75)=180.75 181px。

下面的例子:

<svg id="svg" width="270" height="270">
    <circle id="circle"
            r="115" cx="135" cy="135"
            fill="none";
            stroke="blue"
            stroke-dasharray="723"
            stroke-dashoffset="361"
            stroke-width="15">
        <animate id="animation" 
        attributeName="stroke-dashoffset"  
        attributeType="CSS" 
        begin="0s" 
        to="361"
        from="723"
        dur="2s"/>
  </circle>
            
            <text x="50%" y="50%" text-anchor="middle" stroke="#000" stroke-width="2px" dy=".3em">50%</text>
</svg>

<svg id="svg" width="270" height="270">
    <circle id="circle"
            r="115" cx="135" cy="135"
            fill="none";
            stroke="blue"
            stroke-dasharray="723"
            stroke-dashoffset="181"
            stroke-width="15">
        <animate id="animation" 
        attributeName="stroke-dashoffset"  
        attributeType="CSS" 
        begin="0s" 
        to="181"
        from="723"
        dur="2s"/>
  </circle>
            
            <text x="50%" y="50%" text-anchor="middle" stroke="#000" stroke-width="2px" dy=".3em">75%</text>
</svg>

关于javascript - 根据设置的百分比包围对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46765860/

相关文章:

javascript - `the page is being unloaded` 错误

javascript - 如何使用 javascript、css、html 在网站表单的文本输入字段中放置一个按钮

javascript - 双击以更改复选框 Safari

html - 按钮不会进入导航栏

javascript - 如何将.csv 中的数据加载到数据表中?

javascript - 使用javascript检查图像名称

javascript - 如何使 Switcher Panel 的链接反射(reflect) 'show' 类?

javascript 使用 this.prototype 设置原型(prototype)

javascript - 如何使用javascript获取并返回数组的每个最后一个字符为大写?

html - 向html标签添加属性?