I got the idea for doing something of the kind when I stumbled across this interactive SVG pie chart. While the SVG code is as compact as it gets (a single element!), using strokes for creating pie chart slices is problematic as we run into rendering issues on Windows for Firefox and Edge. Plus, in 2018, we can accomplish a lot more with a lot less JavaScript!
I managed to get the following result using a single HTML element for the chart and very little JavaScript. The future should completely eliminate the need for any JavaScript, but more on that later.
AnimatedAnimatedThe final pie chart result.
Some of you may remember Lea Verou’s Missing Slice talk—my solution is based on her technique. This article dissects how it all works, showing what we can do in terms of graceful degradation and other ways this technique can be put to use.
We use Pug to generate the HTML from a data object that contains unitless percentage values for the past three years:
– var data = { 2016: 20, 2017: 26, 2018: 29 }
We make all our elements reside in a .wrap element. Then, we loop through our data object and, for each of its properties, we create a radio input with a corresponding label. After these, we add a .pie element to the mix.
– var darr = [], val;
– for(var p in data) {
– if(!val) val = data[p];
input(id=`o${p}` name=o type=radio checked=val == data[p])
label(for=`o${p}`) #{p}
– darr.push(`${data[p]}% for year ${p}`)
– }
.pie(aria-label=`Value as pie chart. ${darr.join(, )}.`
role=graphics-document group)
The above Pug code compiles to the following HTML: