【发布时间】:2017-11-03 00:30:50
【问题描述】:
我动态创建我的 chartjs 图例。
我希望我的图表能够垂直动态扩展以适应父级,我使用图表选项中的maintainAspectRatio: false 属性来做到这一点。
我还希望我的图例和图表适合父容器。问题是chartjs没有看到动态生成的图例,给图表一个height的480px。这意味着图例被推到父容器之外,而不是放入其中。
这是一个显示问题的 jsfiddle:
http://jsfiddle.net/vrwjfg9z/4292/
如何动态生成图例,同时告诉 chartjs 将其高度考虑在内,这样它就不会将图例推到其容器之外?
Javascript:
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 20, 81, 56, 55, 40],
}
]
};
var options = {
legend: {
display: false,
},
maintainAspectRatio: false,
scales: {
yAxes:[{
stacked:true,
gridLines: {
display:true,
color:"rgba(255,99,132,0.2)"
}
}],
xAxes:[{
gridLines: {
display:false
}
}]
}
}
var canvas = document.getElementById("myChart");
var myChart = Chart.Bar(canvas, {
data: data,
options: options,
});
// Note - tooltipTemplate is for the string that shows in the tooltip
// legendTemplate is if you want to generate an HTML legend for the chart and use somewhere else on the page
// e.g:
document.getElementById('js-legend').innerHTML = "This dynamically generated line of text should be within chart-container but it is incorrect"
HTML:
<div class='root'>
<div class='chart-container'>
<div class='chart'>
<canvas id="myChart" style="width: 100%; height: auto;"></canvas>
</div>
<div>This line of text should be within chart-container and it is correct</div>
<div id="js-legend"></div>
</div>
</div>
CSS:
.root {
height: 500px;
}
.chart-container {
display: flex;
flex-direction: column;
border: solid 2px red;
height: 100%;
position: relative;
width: 500px;
}
.chart {
flex: 1;
}
【问题讨论】:
标签: javascript css chart.js