我使用angular2工作ChartJS组件。我想知道是否有任何方式呈现为this image。
基本上,条形图在网格上呈现。例如,当我单击列栏时,应显示水平线,并在列栏下的确切月份显示向上箭头。你有什么建议吗?提前谢谢。
答案 0 :(得分:0)
您可以捕获画布的onclick
事件,并使用getElementAtEvent
chartjs方法检查已单击的栏。 getElementAtEvent
为您提供所需的所有相关信息(图表宽度,条形图的x坐标,标签等),以便在图表下方绘制自定义行。
canvas.onclick = function (evt) {
var activePoints = myBarChart.getElementAtEvent(evt);
if (activePoints[0]) {
//draw your custom line
}
};
下面的代码段有两个画布。一个用于绘制实际图表的chart.js,另一个用于绘制带有单击标签文本的行。
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
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 option = {
scales: {
yAxes: [{
stacked: true,
gridLines: {
display: true,
color: "rgba(255,99,132,0.2)"
}
}],
xAxes: [{
gridLines: {
display: false
}
}]
}
};
var myBarChart = Chart.Bar(canvas, {
data: data,
options: option
});
canvas.onclick = function (evt) {
var activePoints = myBarChart.getElementAtEvent(evt);
if (activePoints[0]) {
var chart = activePoints[0]._chart;
var canvasX = document.getElementById('xAxis2');
// set the width of the second canvas to the chart width
canvasX.width = chart.width;
var canvas2D = canvasX.getContext('2d');
// draw the line
canvas2D.moveTo(0, 20);
canvas2D.lineTo(activePoints[0]._view.x - 10, 20);
canvas2D.lineTo(activePoints[0]._view.x, 0);
canvas2D.lineTo(activePoints[0]._view.x + 10, 20);
canvas2D.lineTo(canvasX.width, 20);
canvas2D.stroke();
// add the label text
canvas2D.font = '12px serif';
canvas2D.fillText('for ' + activePoints[0]._view.label, canvasX.width - 100, 15);
}
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
<canvas id="xAxis2" height="20"></canvas>
&#13;