Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<button onclick='init()'>randomize</button><br>
<span id="donut"></span>



            
          
!
            
               label {
    display: block;
  }
  span {
    display: inline-block;
  }
  path.label {
    stroke-width: 1.4;
    stroke: black;
  }
  text {
    font-size: 16px;
    font-family: arial;
    dominant-baseline: middle;
    text-anchor: middle;  
  }
            
          
!
            
              init();  

function init(){

  let count = 3 + Math.floor(Math.random() * 3);  
  let data = Array(count).fill(0).map((d, i) => {
    return { value: 111 + 111*Math.random(), selected: true }
  });

  let size = 300, time = 500; 
  let colors = d3.scaleOrdinal(d3.schemeCategory10);
  let donut =  d3.select('#donut').html(' ');
    
  donut.append('span').selectAll('input')
    .data(data).enter()
    .append('label').style('background-color', (d, i) => colors(i))
    .append('input').attr('type', 'checkbox').attr('checked', true)
    .on("change", function (d) { 
      update(d.selected = this.checked); 
    });

  let svg = donut.append('span').append("svg")
              .attr("viewBox", `-${size} -${size/2} ${size*2} ${size}`).attr("height", size);


  let pie = d3.pie().sort(null);
  let arc = d3.arc().innerRadius(size/3.1-30).outerRadius(size/3.1)
                    .cornerRadius(33);
  let arc2 = d3.arc().innerRadius(size/2.7).outerRadius(size/2.7);
  let arc3 = d3.arc().innerRadius(size/2.2).outerRadius(size/2.2);
  let line = d3.line();

  let d = pie(data.map(d => d.value)).map(d=>{
      d.value &&(d.endAngle+=0.3);
      return d;
  });
    
  let groupsl = svg.selectAll("g.l").data(d)
                  .enter().append("g").attr('opacity', 1);
  let groupsr = svg.selectAll("g.r").data(d)
                  .enter().append("g").attr('opacity', 1);
  let sectorsl = groupsl.append("path").classed("sectorl", true)
    .attr("fill", (d, i) => colors(i));
    
  let sectorsr = groupsr.append("path").classed("sectorr", true)
                      .attr("fill", (d, i) => colors(i));

  let titlesPaths = groupsl.append("path").classed("label", true);

  let titlesTexts = groupsl.append("text").text(d => d.value.toFixed(0));

  let totalText = svg.append('text').style('font-size', 22).attr('y', 2);

               
  sectorsl.transition().duration(time).attrTween('d', growSectorsPathsl); 
  sectorsr.transition().duration(time).attrTween('d', growSectorsPathsr); 
  titlesPaths.transition().duration(time).attr('opacity', 1)
             .attrTween('d', growTitlesPaths); 

  titlesTexts.transition().duration(time)
          .attrTween("x", tweenTitlesTextsX)
          .attrTween("y", tweenTitlesTextsY);
          
  totalText.datum(calcTotal()).transition().duration(time)
           .tween("text", interpolateTotal)

  function update() {
      d = pie(data.map(d => d.selected ? d.value : 0)).map(d=>{
          d.value &&(d.endAngle+=0.3);
          return d;
      });

      sectorsl.data(d).transition().duration(time)
          .attrTween("d", tweenSectorsPathsl);
      sectorsr.data(d).transition().duration(time)
          .attrTween("d", tweenSectorsPathsr);

      groupsl.data(d).transition().duration(time)
          .attr('opacity', d => d.value ? 1 : 0)
      groupsr.data(d).transition().duration(time)
          .attr('opacity', d => d.value ? 1 : 0)
      
      titlesPaths.data(d).transition().duration(time)
          .attrTween("d", tweenTitlesPaths);

      titlesTexts.data(d).transition().duration(time)
          .attrTween("x", tweenTitlesTextsX)
          .attrTween("y", tweenTitlesTextsY);

      totalText.datum(calcTotal()).transition().duration(time)
           .tween("text", interpolateTotal) 
  }

  function growTitlesPaths(d) {
      let i = d3.interpolate(size/4, size/2.7);
      return t => {
        let r = i(t);
        arc2.innerRadius(r).outerRadius(r);
        return line([arc.centroid(this._current = d),arc2.centroid(d)]);
      }
  }

  function growSectorsPathsl(d) {
     let c = (d.startAngle+d.endAngle)/2;
     let il = d3.interpolate(c, d.startAngle);
     return t => {
       d.startAngle = il(t);
       d.endAngle = c+0.2;
       return arc(this._current = d);
     }; 
  }
    
   function growSectorsPathsr(d) {
     let c = (d.startAngle+d.endAngle)/2;
     let ir = d3.interpolate(c, d.endAngle)
     return t => {
       d.startAngle = c-0.2;
       d.endAngle = ir(t);
       return arc(this._current = d);
     }; 
  }

  function tweenSectorsPathsl(d) {
    let i = lerp(this, d);
    return t => {
        let v = i(t);
        v.endAngle = (v.startAngle+v.endAngle)/2+0.2;
        return arc(v);
    };
  }
    
  function tweenSectorsPathsr(d) {
    let i = lerp(this, d);
    return t => {
        let v = i(t);
        v.startAngle = (v.startAngle+v.endAngle)/2-0.2;
        return arc(v);
    };
  }

  function tweenTitlesPaths(d) {
    let i = lerp(this, d);
    return t => line([arc.centroid(i(t)), arc2.centroid(i(t))]);
  }

  function tweenTitlesTextsX(d) {
    let i = lerp(this, d, '_currentX');
    return t => arc3.centroid(i(t))[0];
  }

  function tweenTitlesTextsY(d) {
    let i = lerp(this, d, '_currentY');
    return t => arc3.centroid(i(t))[1];
  }

  function interpolateTotal(d) {
    let i = lerp(this, d);
    return t => Math.round(i(t));
  }

  function lerp(el, d, key){
    key = key || '_current';
    return d3.interpolate(el[key] || 0, el[key] = d);
  }

  function calcTotal() {
    return data.map(d => d.selected ? d.value : 0)
               .reduce((a,v) => a + v, 0)
  }

  function interpolateTotal(d) {
    let that = d3.select(this);
    let i = lerp(this, d);
    return t => that.text(Math.floor(i(t)))
  }
}
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console