使用horizontalbar
和stacked: true
使用ChartJS构建甘特图。我将日期转换为纪元时间,然后转换为天数以在条形图中使用,然后将其转换回日期以在xAxis中显示,但是条形图和xAxis没有正确对齐,因为xAxis的定制Ticks生成的值最小为0,最大为300。
export class AppComponent implements OnInit {
data = [
{task: 'Task 1', startDate: '2018-04-08 00:00:00.000', endDate: '2018-06-08 00:00:00.000'},
{task: 'Task 2', startDate: '2018-05-08 00:00:00.000', endDate: '2018-07-19 00:00:00.000'},
{task: 'Task 3', startDate: '2018-07-08 00:00:00.000', endDate: '2018-09-08 00:00:00.000'},
];
chartData;
options;
plantingDays = this.getDays('2018-04-01 00:00:00.000');
constructor() {
}
createChart() {
const that = this;
this.chartData = {
labels: this.data.map(t => t.task),
datasets: [
{
data: this.data.map(t => {
return this.getDays(t.startDate) - this.plantingDays;
}),
backgroundColor: 'rgba(63,103,126,0)',
hoverBackgroundColor: 'rgba(50,90,100,0)',
},
{
data: this.data.map(t => this.getDays(t.endDate) - this.plantingDays),
},
],
};
this.options = {
maintainAspectRatio: false,
title: {
display: true,
text: 'Title of Chart',
},
legend: {display: false},
tooltips: {
mode: 'index',
callbacks: {
label: function (tooltipItem, d) {
let label = d.datasets[tooltipItem.datasetIndex].label || '';
const data = d.datasets[tooltipItem.datasetIndex].data;
const date = new Date((data[tooltipItem.index] + that.plantingDays) * 86400000);
if (tooltipItem.datasetIndex === 0) {
label += 'Start Date: ' + that.getDate(date);
} else if (tooltipItem.datasetIndex === 1) {
label += 'End Date: ' + that.getDate(date);
}
return label;
},
},
},
scales: {
xAxes: [{
stacked: true,
ticks: {
callback: function (value, index, values) {
const v = (value + that.plantingDays) * 86400000;
console.log(value)
const d = new Date(v);
return that.getDate(d);
},
},
}],
yAxes: [{
stacked: true,
}],
},
};
}
getDate(date) {
return date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).substr(-2)
+ '-' + ('0' + (date.getDay() + 1)).substr(-2);
}
getDays(date) {
return new Date(date).getTime() / 86400000;
}
ngOnInit() {
this.createChart();
}
}