Nal*_*lin 59 javascript chart.js
chart.js的文档提到了"图例模板",但没有提供此类图例的资源或示例.这些如何显示?
小智 58
您可以在图表选项中包含图例模板:
//legendTemplate takes a template as a string, you can populate the template with values from your dataset
var options = {
legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<li>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'
}
//don't forget to pass options in when creating new Chart
var lineChart = new Chart(element).Line(data, options);
//then you just need to generate the legend
var legend = lineChart.generateLegend();
//and append it to your page somewhere
$('#chart').append(legend);
Run Code Online (Sandbox Code Playgroud)
你还需要添加一些基本的CSS以使它看起来不错.
Zan*_*ken 44
图例是ChartJs库的默认选项的一部分.因此,您无需将其明确添加为选项.
该库生成HTML.只需将其添加到您的页面即可.例如,将其添加到给定DIV的innerHTML.(如果您正在编辑颜色,请编辑默认选项等)
<div>
<canvas id="chartDiv" height="400" width="600"></canvas>
<div id="legendDiv"></div>
</div>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "The Flash's Speed",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Superman's Speed",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>
Run Code Online (Sandbox Code Playgroud)
小智 13
奇怪的是,我没有在Chart.js文档中找到任何关于图例和标签的内容.好像你不能单独使用chart.js.
我使用了非常轻的https://github.com/bebraw/Chart.js.legend来生成传说.