I am looking to animate a pie chart with a variable value that is unknown upon loading. Assuming I fetch the value promptly and convert it into a rounded percentage :
var percentage = Math.round(sum * 100 / total);
Next, I place this value here :
<div class="pie animated" id="pie-get-percentage"></div>
$('#pie-get-percentage').html(percentage);
SVG
$(document).ready(function() {
$('#pie-get-percentage').html(percentage);
function $$(selector, context) {
context = context || document;
var elements = context.querySelectorAll(selector);
return Array.prototype.slice.call(elements);
}
$$('.pie').forEach(function(pie) {
var p = parseFloat(pie.textContent);
var NS = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(NS, "svg");
var circle = document.createElementNS(NS, "circle");
var title = document.createElementNS(NS, "title");
circle.setAttribute("r", 16);
circle.setAttribute("cx", 16);
circle.setAttribute("cy", 16);
circle.setAttribute("stroke-dasharray", p + " 100");
svg.setAttribute("viewBox", "0 0 32 32");
title.textContent = pie.textContent;
pie.textContent = '';
svg.appendChild(title);
svg.appendChild(circle);
pie.appendChild(svg);
});
});
CSS
.pie-wrapper {
.pie {
width: 100px;
height: 100px;
display: inline-block;
margin: 10px;
transform: rotate(-90deg);
}
svg {
background: $primary;
border-radius: 50%;
}
circle {
fill: $primary;
stroke: $secondary;
stroke-width: 32;
}
@keyframes grow {
to {
stroke-dasharray: 100 100
}
}
.pie.animated {
animation: grow 2s linear;
}
}
I previously believed that adjusting the .pie.animated
CSS properties would allow me to animate up to the dynamic value, but so far, only the full circle has been animated.
Essentially, if my value is 42%, I aim to expand my circle to reflect 42% of the SVG. However, my challenge lies in applying a dynamic value to the CSS animation. It is possible that using inline CSS might be necessary, but I am uncertain if it can be utilized for animation keyframes.
The JSFiddle link is available here