1 回答

TA贡献1816条经验 获得超6个赞
插件核心 API 提供了一系列可用于执行自定义代码的挂钩。您可以使用钩子直接在画布上使用文本在不同数据点之间绘制不同样式的线条 画布呈现Context2D
。beforeDraw
如果最后一个数据点的颜色也不同,则可以定义为数组。它应该包含每个值的条目,除了最后一个值之外,所有值都是相同的。这可以使用数组.map()
完成,如下所示。dataset.borderColor
borderColor: data_array.map((v, i) => i + 1 == data_array.length ? 'rgb(0, 0, 255)' : 'rgba(255, 99, 132)'),
请看下面的可运行代码片段。
const data_array = [307.65, 309.54, 307.71, 314.96, 313.14, 319.23, 316.85, 318.89, 316.73, 318.11, 319.55];
var myChart = new Chart('myChart', {
type: 'line',
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
ctx.save();
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
data_array.forEach((value, index) => {
if (index > 0) {
var valueFrom = data_array[index - 1];
var xFrom = xAxis.getPixelForTick(index - 1);
var yFrom = yAxis.getPixelForValue(valueFrom);
var xTo = xAxis.getPixelForTick(index);
var yTo = yAxis.getPixelForValue(value);
ctx.lineWidth = 5;
if (index + 1 == data_array.length) {
ctx.setLineDash([5, 5]);
ctx.strokeStyle = 'rgb(0, 0, 255)';
} else {
ctx.strokeStyle = 'rgb(255, 99, 132)';
}
ctx.beginPath();
ctx.moveTo(xFrom, yFrom);
ctx.lineTo(xTo, yTo);
ctx.stroke();
}
});
ctx.restore();
}
}],
data: {
labels: ['2020/05/13', '2020/05/14', '2020/05/15', '2020/05/18', '2020/05/19', '2020/05/20', '2020/05/21', '2020/05/22', '2020/05/26', '2020/05/27', '2020/05/29'],
datasets: [{
label: 'Count',
data: data_array,
tension: 0,
showLine: false,
borderColor: data_array.map((v, i) => i + 1 == data_array.length ? 'rgb(0, 0, 255)' : 'rgba(255, 99, 132)'),
borderWidth: 5
}]
},
options: {
animation: {
duration: 0
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>
添加回答
举报