D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
GitNoise
Full window
Github gist
donut chart
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } .label { position: absolute; text-align: center; font-family: Arial; font-size: 12px; color: #222222; } .label > span { font-size: 28px; font-weight: bold; font-family: TimesNewRomanPS-BoldMT; } </style> </head> <body> <script> var width = 500, height = 300, innerRadius = 80, outerRadius = 100, radius = outerRadius + 25; var data = [ { value: 12, label: "EJ PÅBÖRJADE", color: "#f0f0f0", sufix:'%' }, { value: 22, label: 'GENOMFÖRDA', color: "#6f808c", sufix:'%' }, { value: 66, label: 'EJ GENOMFÖRDA', color: "#f18163", sufix:'%' }, ]; var pie = d3.pie() .value(function(d) { return d.value; }) .sort(null); var arc = d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) .startAngle(d => d.startAngle) .endAngle(d => d.endAngle); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); var slice = svg.append("g") .attr("transform", "translate(" + width/2 + "," + height / 2 + ")") .attr("class", "field") .selectAll(".slice") .data(pie(data)) .enter() .append("g") .classed("slice", true) slice .append("path") .attr("class", "slice path path--background") .attr("d", arc ) .style("fill", d => d.data.color || '#a0a0a0'); slice.each(function(d) { if(d.data.label) { const label = d3.select("body").append("div"); label.html(`<span>${d.value}${d.data.sufix || ''}</span><br/>${d.data.label}`); label.attr("class", "label"); var c = arc.centroid(d), x = c[0], y = c[1], // pythagorean theorem for hypotenuse h = Math.sqrt(x*x + y*y); const labelBcr = label.node().getBoundingClientRect() const compensateX = (d.endAngle + d.startAngle)/2 < Math.PI ? 0 : -labelBcr.width; const compensateY = -labelBcr.height/2; label.attr("style", `top:${height/2 + y/h * radius + compensateY}px; left:${width/2 + x/h * radius + compensateX}px`); } }); </script> </body>
https://d3js.org/d3.v4.min.js