简体   繁体   中英

Chart.js pie chart overflowing div

I'm having trouble getting a Chart.js (v2.6) pie chart to fit into a bootstrap div. The width is responsive, but the height overflows. I have the height set to 210px with statcard-fixed-height as you can see in the fiddle. The box maintains that height but the chart does not.

HTML:

  <div class="row">
    <div class="col-lg-1 m-b">
        <div id="new-old" class="statcard statcard-primary statcard-bg statcard-fixed-height-lg">
            <div class="p-a">
                <span class="statcard-desc">New vs. Returning Users</span>
                <canvas id="myPieChart"></canvas>
            </div>
        </div>
    </div>
  </div> 

JS:

result = [{
    label: "New Users",
    data: 48.8
}, {
    label: "Returning Users",
    data: 51.2
}];

var labels = [],
    data = [];
for (var i = 0; i < result.length; i++) {
    labels.push(result[i].label);
    data.push(result[i].data);
}
var ctx = document.getElementById("myPieChart").getContext("2d");
new Chart(ctx, {
    type: 'pie',
    data: {
        labels: labels,
        datasets: [{
            label: 'New vs Returning Users',
            fill: false,
            backgroundColor: ["#9F86FF", "#1BC98E"],
            lineTension: 0.1,
            data: data
        }]
    },
    options: {
        responsive: true,
        legend: {
            display: true,
            position: 'right',
            labels: {
                fontColor: '#fff'
            }
        },
        elements: {
            arc: {
                borderWidth: 0
            }
        }
    }
});
ctx.height = 100;

Fiddle: https://jsfiddle.net/3d6hqhc1/1/

UPDATE:

Simpler fiddle: https://jsfiddle.net/m80xxxv8/1/

https://github.com/chartjs/Chart.js/issues/2422

Include a holder div and set maintainAspectRatio to false

<div id="canvas-holder" > <canvas id="chart-canvase" /> </div>

var options = { responsive: true, maintainAspectRatio : false };

You need to wrap you chart into a div

#responsive-chart{
   height: 100%;
   width: 100%;
}

<div class="row">
    <div class="col-lg-1 m-b">
        <div id="new-old" class="statcard statcard-primary statcard-bg statcard-fixed-height-lg">
           <div class="p-a">
               <span class="statcard-desc">New vs. Returning Users</span>
                <div id="responsive-chart">
                    <canvas id="myPieChart"></canvas>
                </div>
           </div>
       </div>
    </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM