How to fit Doughnut Chart JS into Bootstrap column?

廉价感情. 提交于 2019-12-11 06:28:43

问题


I want my Doughnut graphic from Chart.js to fit into my bootstrap column. I also want this column to be specific size (actually, I more concerned about height). The problem is that size of canvas div is actually bigger than my column div and all charts overlap on each other. Ideally, I want all 4 charts to be aligned to the right of the row and have a little space from the right (some margin of 10px for example).

I've tried to play around with margin/padding settings on the column div and canvas. Can't figure it out...

Here is jsfiddle example

My HTML:

<div class="row">
  <div class="col-sm-3">
    Some content
  </div>
  <div class="col-sm-3">
    Some other content
  </div>

  <div class="col-sm-2"></div>

  <div class="col-sm-1">
    <div class="chart-container" style="position: relative; width: 200px; height: 100px;">
      <canvas id="chart1" width="200" height="100"></canvas>
    </div>
  </div>
  <div class="col-sm-1">
    <div class="chart-container" style="position: relative; width: 200px; height: 100px;">
      <canvas id="chart2" width="200" height="100"></canvas>
    </div>
  </div>
  <div class="col-sm-1">
    <div class="chart-container" style="position: relative; width: 200px; height: 100px;">
      <canvas id="chart3" width="200" height="100"></canvas>
    </div>
  </div>
  <div class="col-sm-1">
    <div class="chart-container" style="position: relative; width: 200px; height: 100px;">
      <canvas id="chart4" width="200" height="100"></canvas>
    </div>
  </div>
</div>

And my JS:

var myNewChart;
var data = [{
  value: 30,
  color: "#F7464A"
}, {
  value: 50,
  color: "#E2EAE9"
}, {
  value: 100,
  color: "#D4CCC5"
}, {
  value: 40,
  color: "#949FB1"
}, {
  value: 100,
  color: "#4D5360"
}];

var options = {
  animation: true,
  animationEasing: 'easeInOutQuart',
  animationSteps: 80
};

//Get the context of the canvas element we want to select
var ctx1 = document.getElementById("chart1")
  .getContext("2d");
var ctx2 = document.getElementById("chart2")
  .getContext("2d");
var ctx3 = document.getElementById("chart3")
  .getContext("2d");
var ctx4 = document.getElementById("chart4")
  .getContext("2d");

/*******************************************************/
myNewChart1 = new Chart(ctx1).Doughnut(data, options);
myNewChart2 = new Chart(ctx2).Doughnut(data, options);
myNewChart3 = new Chart(ctx3).Doughnut(data, options);
myNewChart4 = new Chart(ctx4).Doughnut(data, options);

回答1:


You can add some CSS to properly style Chart.js canvas and div container:

canvas {
  width: 100%;
  height: 100%;
  display: block;
}

div.chart-container {
  padding: 1px;
}

Check this fiddle updated: http://jsfiddle.net/beaver71/ht7uevay/



来源:https://stackoverflow.com/questions/48216621/how-to-fit-doughnut-chart-js-into-bootstrap-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!