use*_*562 5 javascript chart.js
让我说我有一个与周一4周的折线图.我希望这4周分为几个部分.我希望星期一的第一个星期一有白色背景颜色.星期五的第二个星期一灰色背景.再次出现白色bg.星期一到星期五的第四周有一个灰色的背景色.我所说的是图表的背景.有没有办法做到这一点?
Chart.js在绘制(或重绘)图表之前清除画布.
我们可以跳过这个并在图表清除后绘制我们的背景.只需扩展折线图并覆盖初始化覆盖中的清除功能.
预习
脚本
Chart.types.Line.extend({
name: "LineAlt",
initialize: function(data){
Chart.types.Line.prototype.initialize.apply(this, arguments);
// keep a reference to the original clear
this.originalClear = this.clear;
this.clear = function () {
this.originalClear();
// 1 x scale unit
var unitX = this.datasets[0].points[1].x - this.datasets[0].points[0].x;
var yTop = this.scale.startPoint;
var yHeight = this.scale.endPoint - this.scale.startPoint;
// change your color here
this.chart.ctx.fillStyle = 'rgba(100,100,100,0.8)';
// we shift it by half a x scale unit to the left because the space between gridline is actually a shared space
this.chart.ctx.fillRect(this.datasets[0].points[5].x - 0.5 * unitX, yTop, unitX * 5, yHeight);
this.chart.ctx.fillRect(this.datasets[0].points[15].x - 0.5 * unitX, yTop, unitX * 5, yHeight);
}
}
});
Run Code Online (Sandbox Code Playgroud)
然后只使用LineAlt而不是Line
var myNewChart = new Chart(ctx).LineAlt(data);
Run Code Online (Sandbox Code Playgroud)
小提琴 - http://jsfiddle.net/oe2606ww/
这里的一些人要求一些适用于更高版本的东西,这是我在 ChartJS 2.7.2 (编辑:2020 年 4 月:也是 2.9.3)上工作的黑客组合解决方案,并且可能会进行调整。 Chart.types.Line.extend在上面的答案中使用,似乎在 v2 中无效。

我设法在此线程的帮助下弄清楚了这一点以获取插件代码,并且还发现此线程对于收集数据点的坐标很有用。
通过一些工作,这个小提琴应该允许您通过以下代码将标签数组键作为开始/停止位置传递(其中 0 和 1 是键):
var start = meta.data[0]._model.x;
var stop = meta.data[1]._model.x;
Run Code Online (Sandbox Code Playgroud)
你可以循环这个,以及ctx.fillRect绘制多个矩形的函数。
这是工作小提琴:http : //jsfiddle.net/oe2606ww/436/