Simple circular graph to enhance a number (HTML, CSS and SVG)
Par arthur-and-ashes,
Publié le April 23, 2020
I looked for a way to enhance a number, a percentage or a rate. I had already seen these VG graph and I thought it was very complex. But it was also very efficient to visualise a rate.
Some JS library enables to make very complex graphs on the web. But here, I needed to find a very simple way to draw a graph with SVG. That’s why I decided to create a very simple circular path with SVG.
Mise en pratique sur codepen.
Code a circle with SVG
Normally, it is common to use a dedicated software to draw vectors (Like Illustrator). But here, we are going to write very simple SVG tags. I open a <svg>
tag and I insert a new <path>
tag. (I could have used this tag instead <circle>
).
Here I draw a SVG circle :
<svg viewBox="0 0 36 36" class="circle-svg"> <path class="around" stroke-dasharray="100, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"></path> </svg>
I choose the <path> tag here because it will enable me to create the arc of a circle. The attribute “stroke-dashaway” defines the outline of the circle. Here I want to draw a conuinue line to the end of the circle. So I write the maximum values (“100, 100”).
Note that “stroke-dasharray” is a CSS value and we could have used it directly in the CSS.
Now I will create a second arc of circle in blue :
<svg viewBox="0 0 36 36" class="circle-svg"> <path class="around" stroke-dasharray="100, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"></path> <path class="percent" stroke-dasharray="30, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"></path> <text x="18" y="14" text-anchor="middle" dy="7" font-size="20">3/10</text> </svg>
My second tag is similar to the first one, excerpt from this value stroke-dasharray, set to 30, 100. This is corresponding to a 30% arc. Be careful, this attribute is not corresponding to a percent value.
.circle-svg { display: block; margin: 10px auto; max-height: 100px; } .circle-svg text { text-align:center; color:black; font-size:10px } .circle-svg path.percent { stroke: #6f6fff; fill: none; stroke-width: 2.8; stroke-linecap: round; animation: progress 1s ease-out forwards; } .circle-svg path.around { stroke: #c4c4c4; fill: none; stroke-width: 2.8; }
Now I am going to animate this arc with this rule in CSS :
@keyframes progress { 0% { stroke-dasharray: 0 100; } }