Chartjs自定义动态图例溢出

时间:2017-11-02 12:59:31

标签: javascript css chart.js

我动态创建了我的chartjs图例。

我希望我的图表能够垂直动态扩展以适合父级,我在图表选项中使用maintainAspectRatio: false属性执行此操作。

我还希望我的图例和图表适合父容器。问题是chartjs没有看到动态生成的图例,并为图表提供height 480px。这意味着图例被推到父容器之外而不是装在其中。

这是一个显示问题的小提琴手:

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;
}

1 个答案:

答案 0 :(得分:1)

在.chart-container上将高度更改为auto,并将min-height添加为100%。

.chart-container {
  display: flex;
  flex-direction: column;
  border: solid 2px red;
  height: auto;
  min-height: 100%;
  position: relative;
  width: 500px;
}

http://jsfiddle.net/o0Lok3y0/

添加图例后,您可以添加javascript来更改图表的高度。

var legend = document.getElementById('js-legend'),
    canvas = document.getElementById('myChart');

legend.innerHTML = "This dynamically generated line of text should be within chart-container but it is incorrect"

var legendStyle = window.getComputedStyle(legend),
    canvasStyle = window.getComputedStyle(canvas),
    legendHeight = legendStyle.height.replace("px", ""),
    canvasHeight = canvasStyle.height.replace("px", "");

canvas.style.height = (canvasHeight - legendHeight) + 'px';

http://jsfiddle.net/7m7hbrhn/