The realization method of generating circular progress bar by HTML svg

Time:2020-2-6

Previously, I met the requirement of a circular progress bar in the project, which requires that the progress can be updated in real time, and the scheme in CSS, SVG, and canvas will pop up in my mind in an instant. For the three schemes, I prefer SVG, which is simple to use, with little code, and easy to control in real time. The specific effect is as follows:

The code is very simple:


<svg width="150px" height="150px" class="svg">
    <circle r="70" cy="75" cx="75" stroke-width="8" stroke="#EAEFF4" stroke-linejoin="round" stroke-linecap="round" fill="none"/>
    <circle class="progress" r="70" cy="75" cx="75" stroke-width="8" stroke="#1593FF" stroke-linejoin="round" stroke-linecap="round" fill="none" stroke-dashoffset="0px"  stroke-dasharray="471px" />
</svg>

To facilitate the demonstration, we use CSS animation to control:


svg {
    transform: rotate(-90deg);
}
.progress {
    animation: rotate 1500ms linear both;
}
@keyframes rotate {
    from {
        stroke-dashoffset: 471px;
    }
    to {
        stroke-dashoffset: 0px;
    }
}

Realization principle

The principle of implementation is very simple, that is to apply the stroke dasheffset and stroke dasharray attributes of SVG.

stroke-dasharray

It is officially interpreted as a pattern pattern pattern that can control the dashes used for edge tracing, that is, to define the length of each segment of the dashes, that is, the interval between dashes, the comma or blank between numbers, and to specify the length of the dashes and notches. If an odd number of values is provided, the sequence of values is repeated once, resulting in an even number of values.

stroke-dashoffset

Identifies the offset value of the entire path.

By controlling the interval and offset value of the dotted line, we can travel all kinds of line animation. Of course, we can also control through JS, as follows:

let path = document.querySelector('#path');
//Length of available paths
let len = path.getTotalLength();
path.style.cssText = `stroke-dasharray:"${number}"`;

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

The first Python Programming challenge on the Internet (end)

Date of establishment: March 28, 2020Update Date: April 22, 2020 (end)Personal collection Tool.pywebsite:http://www.pythonchallenge.com/Note: please quote or change this article at will, just mark the source and the author. The author does not guarantee that the content is absolutely correct. Please be responsible for any consequences Title: the first Python Programming challenge on the web Find […]