该 插件核心API 提供了一系列可用于执行自定义代码的钩子。您可以使用 afterDraw
钩子来直接在画布上绘制图像,而不是使用 CanvasRenderingContext2D
.
你还必须指示Chart.js不显示默认的tick标签。这可以通过在图表选项中的以下定义来实现。
scales: {
xAxes: [{
ticks: {
display: false
}
}],
此外,你还需要在图表的底部和右侧定义一些padding,否则你将只能看到部分图片。
layout: {
padding: {
bottom: 30,
right: 15
}
},
请看下面的可运行代码片段。
const labels = ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png'];
const values = [48, 56, 33, 44];
new Chart(document.getElementById("myChart"), {
type: "line",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
var image = new Image();
image.src = images[index],
ctx.drawImage(image, x - 12, yAxis.bottom + 10);
});
}
}],
data: {
labels: labels,
datasets: [{
label: 'My Dataset',
data: values,
fill: false,
backgroundColor: 'green',
borderColor: 'green'
}]
},
options: {
responsive: true,
layout: {
padding: {
bottom: 30,
right: 15
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 20
}
}],
xAxes: [{
type: 'time',
time: {
unit: 'day',
tooltipFormat: 'MMM DD'
},
ticks: {
display: false
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>