Search code examples
javascripthtmlcanvaschart.js

Cutout percentage in data chart


How would I add cutout percentage to my data chart in chart js, the aim id to make the chart thiner.

const data = {
  labels: ['onek', 'teo', 'Three'],
  datasets: [{
    data: [1, 3, 9],
    backgroundColor: [],
    borderColor: [],
    hoverOffset: 4
  }]
};


var chart = new Chart(document.getElementById('myChart'), {
  type: 'doughnut',
  data: data,
  options: {
    responsive: true,
    legend: {
      display: false
    },
  }
});

jQuery(function($) {
  // Function that formats a raw price amount
  function formatPrice(rawPrice) {
    return rawPrice.toLocaleString("en-US", {
      style: "currency",
      currency: "USD"
    });
  }

  $('form#roi').on('click', '.calculate-roi', function() {
    // update chart 
    chart.data.datasets.pop();
    chart.data.datasets.push({

      data: [mr_results_total, ea_results_total, rav_results_total],
      backgroundColor: [
        'rgb(255, 99, 132)',
        'rgb(54, 162, 235)',
        'rgb(255, 205, 86)'
      ],
      hoverOffset: 4,
    });

    Chart.pluginService.register({
      beforeDraw: function(chart) {

        var width = chart.chart.width,
          height = chart.chart.height,
          ctx = chart.chart.ctx;

        ctx.restore();

        ctx.beginPath();
        var fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.arc(width / 2, height / 2, 80, 0, 2 * Math.PI);
        ctx.fillStyle = '#8AC007';
        ctx.fill();
        ctx.lineWidth = 5;
        ctx.fillStyle = 'blue';
        ctx.strokeStyle = '#003300';
        ctx.stroke();
        ctx.fillText(text, textX, textY);
        ctx.save();



        var text = total_number,
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = height / 2;

        ctx.fillText(text, textX, textY);
        ctx.save();
      }
    });

    chart.update();

  });
});


var slider = document.getElementById("myRange");
var output = document.getElementById("demo");

// var slider2 = document.getElementById("myRange2");
// var output2 = document.getElementById("demo2");
output.innerHTML = slider.value;
// output2.innerHTML = slider2.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
#output {
  display: none;
  font-size: 26px;
  margin-top: 50px;
}

.help-inline {
  display: none;
}

.result {
  padding-top: 10px;
}

.roi-success {
  background: #269526;
  color: white;
}

.roi-danger {
  background: #d74e26;
  color: white;
}

input[type="text"] {
  width: 100%;
  display: block;
  margin: 15px 0;
}

.btn {
  display: block;
}

.double-border {
  --b: 2px;
  /* thickness */
  --c: #3CD5AF;
  height: 100%;
  border-right: var(--b) solid var(--c);
  border-left: var(--b) solid var(--c);
  background: linear-gradient(var(--c) 0 0) left 10px bottom 0/var(--b) 50% no-repeat, linear-gradient(var(--c) 0 0) right 10px bottom 0/var(--b) 50% no-repeat
}

.slider {
  width: 100%;
  border-radius: 5px;
  background: #00AFAB;
  outline: none;
  opacity: 0.7;
  -webkit-transition: .2s;
  transition: opacity .2s;
  padding: 0 0 0 0;
  margin: 0;
}

.slider:hover {
  opacity: 1;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #00AFAB;
  cursor: pointer;
}

.slider::-moz-range-thumb {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #04AA6D;
  cursor: pointer;
}

select {
  width: 75%;
}

#output {
  font-size: 16px;
  margin-top: 0;
}

.chartbox {
  width: 100;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>
<section <?php theme_section_attr_id() ?>
  <?php theme_section_attr_class( 'pb-5' ) ?>>
  <div class="container">
    <div class="row pt-5">
      <div class="col-md-4 pt-5">
        <div class="heading ">
        </div>
      </div>
      <div class="col-md-8 border">
        <div class="row p-5 pb-0">
          <div class="col-md-6">
            <form id="roi">
              <div class="control-group">
                <p>Number <span id="demo"></span></p>
                <div class="slidecontainer">
                  <input id="no_emp" type="range" min="50" max="50000" value="50" class="slider" id="myRange">
                </div>
                <p>Monthly <span id="demo2"></span></p>
                <div class="slidecontainer">
                  <input id="month_inv" type="range" min="10" max="1000" value="10" class="slider" id="myRange2">
                </div>
              </div>
              <button type="button" class="btn btn-primary btn-block calculate-roi">Calculate</button>
            </form>
          </div>
          <div class="col-md-6 text-center">
            <div class="chartbox">
              <canvas id="myChart"></canvas>
            </div>
            <p>Estimated Value</p>
            <h3 class="total_number"></h3>
          </div>
        </div>
      </div>
    </div>

  </div>
</section>


Solution

  • With Chart.js version 2, you need to apply the cutoutPercentage config in options. The value represents the percentage

    options: {
      ...,  
      cutoutPercentage: 80,
    },
    

    For Chart.js version 3 and above, the cutout config should be provided with value based on description

    The portion of the chart that is cut out of the middle. If string and ending with '%', percentage of the chart radius. number is considered to be pixels.

    options: {
      ...,  
      cutout: '80%',
    },
    

    Demo @ StackBlitz