简体   繁体   中英

SVG Path 'D' attribute half circle progress

I want to make a bar in a half circle that turns towards the clockwise direction. I can do it using the stroke-dasharray . I want to do half circle progress bar. I have to do this counterclockwise by giving a percentage

<svg viewBox="0 0 110 110">
  <path
        d="M 5 5 A 50 50 0 0 0 105 5"
        fill="none"
        stroke="blue"
        stroke-width="2" />
</svg>

Method 1: Calculate mathematically

You can get the length of the semicircle by using maths to calculate the length of the semicircle.

Your circle has radius 50. So the circumference of the circle will be 2 * 50 * PI or 314.15... Then we need to divide that in half, because you only have half a circle.

 function setProgress(percent) { var bar = document.getElementById("progress"); var barLength = (2 * 50 * Math.PI) / 2; var dashLength = percent * barLength / 100; bar.setAttribute("stroke-dasharray", dashLength + " " + barLength); } setProgress(45);
 <svg viewBox="0 0 110 110"> <path id="progress" d="M 5 5 A 50 50 0 0 0 105 5" fill="none" stroke="blue" stroke-width="2" /> </svg>

Method 2: using getTotalLength()

But that method requires that you know in advance that the size of the circle is 50. There is a better way. We can get the length of the semicircle by calling getTotalLength() on the path element. The rest of the process is the same.

 function setProgress(percent) { var bar = document.getElementById("progress"); var barLength = bar.getTotalLength(); var dashLength = percent * barLength / 100; bar.setAttribute("stroke-dasharray", dashLength + " " + barLength); } setProgress(45);
 <svg viewBox="0 0 110 110"> <path id="progress" d="M 5 5 A 50 50 0 0 0 105 5" fill="none" stroke="blue" stroke-width="2" /> </svg>

Method 3: pathLength

One final method relies on a special attribute of <path> elements called pathLength .

By adding pathLength="100" to the <path> , we are telling the browser to pretend that the path has length 100 when calculating dash lengths and offsets. So that means we can use our percentage values directly, when setting the dash pattern.

The drawback to this is that some older browsers don't support pathLength , or they have bugs with it. For example, this method does not work in IE. If you need to support older browsers, use method 2 instead.

 function setProgress(percent) { var bar = document.getElementById("progress"); bar.setAttribute("stroke-dasharray", percent + " 100"); } setProgress(45);
 <svg viewBox="0 0 110 110"> <path id="progress" d="M 5 5 A 50 50 0 0 0 105 5" fill="none" stroke="blue" stroke-width="2" pathLength="100"/> </svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM