Drawing circular path with svg and controlling its

2019-08-20 13:03发布

问题:

Is it possible to draw a circular path like this

via svg paths in a way where it is possible to manipulate it to either be 100% (so full circle) or stop at 50%, so top to bottom forming half a circle. Note 100% and 50% are examples used, in real world any percentage from 0 to 100 should be valid.

After some research I found that following approach seems to be how you draw a circle https://stackoverflow.com/a/8193760/911930 but I don't see any way to implement this where I can draw / stop path at a given percentage.

回答1:

There are numerous examples of how to do this, here on Stack Overflow, and elsewhere on the web. But they all will use one of two methods to draw the progress bar:

  1. Construct a <path> element using one or more path arc ('A') commands
  2. Use a <circle> and use a dash pattern to draw part of a circle

The second one is the easier of the two to implement. Hopefully the example below is straightforward to follow:

function setProgress(percent)
{
  // Pointer to the <circle> element
  var progress = document.getElementById("progress");
  // Get the length of the circumference of the circle
  var circumference = progress.r.baseVal.value * 2 * Math.PI;
  // How long our stroke dash has to be to cover <percent> of the circumference?
  var dashLength = percent * circumference / 100;
  // Set the "stroke-dasharray" property of the cicle
  progress.style.strokeDasharray = dashLength + ' ' + circumference;
}

setProgress(55);
svg {
  width: 300px
}

#progress {
  fill: lightgrey;
  stroke: orange;
  stroke-width: 10;
}
<svg viewBox="-100 -100 200 200">
  <circle id="progress" r="80" transform="rotate(-90)"/>
</svg>



回答2:

i think you are approaching this problem in the wrong direction;

you should search on the internet for a circular progress bar, you will find tons of answers.

this is one link: https://kimmobrunfeldt.github.io/progressbar.js/