【发布时间】:2021-07-31 06:47:42
【问题描述】:
我正在尝试用不同颜色的利润和损失制作利润图表,到目前为止,我扩展了默认折线图
Chart.defaults.ProfitLossLine = Chart.helpers.clone(Chart.defaults.line);
Chart.controllers.ProfitLossLine = Chart.controllers.line.extend({
update: function () {
// get the min and max values
const dataset = this.chart.data.datasets[0];
const min = Math.min.apply(null, dataset.data);
const max = Math.max.apply(null, dataset.data);
const yScale = this.getScaleForId(this.getMeta(0).yAxisID);
// figure out the pixels for these and the value 0
const top = yScale.getPixelForValue(max);
const zero = yScale.getPixelForValue(0);
const bottom = yScale.getPixelForValue(min);
// build a gradient that switches color at the 0 point
const ctx = this.chart.chart.ctx;
const gradient = ctx.createLinearGradient(0, top, 0, bottom);
const ratio = Math.min((zero - top) / (bottom - top), 1);
gradient.addColorStop(0, dataset.positiveBorderColor);
gradient.addColorStop(ratio, dataset.positiveBackgroundColor);
gradient.addColorStop(ratio, dataset.negativeBackgroundColor);
gradient.addColorStop(1, dataset.negativeBorderColor);
dataset.borderColor = gradient;
dataset.backgroundColor = gradient;
dataset.pointBorderColor = gradient;
dataset.pointBackgroundColor = gradient;
dataset.pointHoverBorderColor = gradient;
dataset.pointHoverBackgroundColor = gradient;
this.chart.options.legend.labels.generateLabels = (chart) => {
const labels = Chart.defaults.global.legend.labels.generateLabels(chart);
for (const key in labels) {
labels[key].fillStyle = gradient;
labels[key].strokeStyle = gradient;
}
return labels;
}
return Chart.controllers.line.prototype.update.apply(this, arguments);
}
});
得到了
但我想在“利润”的图例框中应用相同的绿-红渐变,它实际上是灰色的。
【问题讨论】:
标签: javascript charts chart.js