【发布时间】:2020-05-25 02:49:11
【问题描述】:
我目前正在将chart.js 折线图从 v1 升级到 v2,遇到了一个障碍。
图表数据包含featured 属性下的布尔数组customOptions。
var chartData = {
labels: [
"14th Jan",
"15th Jan",
"16th Jan",
"17th Jan",
"18th Jan",
"19th Jan"
],
datasets: [{
label: "Listing Popularity",
data: [
1199,
575,
407,
313,
181,
268
],
}],
customOptions: {
featured: [
false,
false,
false,
false,
false,
true
]
}
}
var ctx = document.getElementById('chartjs-chart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'PPLine',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
});
我创建了一个折线图的扩展版本,它循环遍历图表customOptions 中的featured 数组,并在featured 布尔值返回true 时添加路径
Chart.controllers.PPLine = Chart.controllers.line.extend({
draw: function () {
var that = this;
var helpers = Chart.helpers;
var xScale = that._xScale;
var ctx = that.chart.ctx;
// Draw chart
Chart.controllers.line.prototype.draw.call(that, arguments);
helpers.each(that.chart.data.customOptions.featured, function (featured, index) {
var meta = that.chart.getDatasetMeta(0);
var linePos = meta.data[index]._model.x,
endLinePos = that.chart.options.elements.point.borderWidth + (meta.data[index + 1] ? meta.data[index + 1]._model.x : linePos);
// Draw featured sections
if (featured) {
var centerX = meta.data[index]._model.x;
var centerY = meta.data[index]._model.y;
var radius = 30;
// Draw boost circle
ctx.save();
ctx.beginPath();
ctx.fillStyle = that.chart.data.customOptions.bumpedColour;
ctx.lineWidth = 10;
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fill();
ctx.restore();
// Add text
ctx.save();
ctx.beginPath();
ctx.fillStyle = "#fff";
ctx.font = "10px " + that.chart.config.options.defaultFontFamily;
ctx.fillText("Boost", centerX - (ctx.measureText('Boost').width / 2), centerY + 3);
ctx.fill();
ctx.restore();
}
});
}
});
当featured 数组中的最后一项是true 并且路径被添加到该点时,问题就出现了,从视觉上看,路径被切断了,所以我需要在图表中添加一些填充以防止这种情况发生.
在 V1 中,我能够在扩展折线图中执行以下操作...
var that = this;
that.scale.xScalePaddingRight = 20;
但是,比例不是 v2 对象中的属性。有一个_xScale 属性和一个paddingRight 属性,但是执行以下操作似乎没有添加所需的填充,因此路径不会被切断。
var that = this;
that._xScale.paddingRight = 20;
这里是CodePen 的问题。
我不想在每个实例中都添加填充,只是在最后一个点出现并且路径被绘制时。
任何帮助将不胜感激。
【问题讨论】:
标签: javascript jquery chart.js