为什么chart.js图表没有在Safari中绘制数据(适用于Chrome)



我在chart.js中创建了几个图表,它们在chrome中运行良好,但当我在Safari中查看它们时,其中两个图表没有绘制数据,只显示了图表的外壳。

这些代码完全相同。我正在提取csv文件。我能看到的唯一区别是,不起作用的CSV在数据中包含月份和年份。如何修复代码,使其显示在Safari和Chrome中?这是我的约会设置吗。我在Chrome中也收到了这个奇怪的消息(见下文,看起来也与日期问题有关(。

这种类型的数据工作正常:

"1980","2.4"
"1981","2.6"
"1982","2.7"

此数据不:

"May 2016","6.9"
"June 2016","6.8"
"July 2016","7.0"

这是我的代码:

window.addEventListener('load', setup);
async function setup() {
var ctx = document.getElementById('myChart').getContext('2d');
var dollar = await getData();
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: dollar.years,
datasets: [
{label: 'Unemployment rate',
data: dollar.vals,
borderColor: 'rgb(153,222,101)',
backgroundColor: 'rgb(153,222,101, 0.2)',
pointRadius: 0,
borderWidth: 6,
pointHitRadius: 10,
}]
},
options: {
layout: {
padding: {
left: 0,
right: 15,
top: 0,
bottom: 0}
},
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 3,
max: 8,
stepSize: 1
}
}],
xAxes: [{
type: "time",
time: {
unit: "year",
tooltipFormat: "YYYY"
},
gridLines: {
display: true,
drawOnChartArea: false,
},
ticks: {
display: true,
maxTicksLimit: 5,
maxRotation: 0,
minRotation: 0,
padding: 1
},
}],
}
}
});
}

这是我在Chrome中遇到的错误。

弃用警告:提供的值不是可识别的RFC2822或ISO格式。moment构造又回到了js Date((,它在所有浏览器和版本中都不可靠。不鼓励使用非RFC2822/ISO日期格式,并将在即将发布的主要版本中删除。请参阅http://momentjs.com/guides/#/warnings/js-日期/了解更多信息。

问题在于解析日期字符串。Chart-js对日期字符串使用矩适配器,这种类型("2016年5月"(的格式在一些浏览器中可能不容易解析,看看你可以使用什么样的格式https://momentjs.com/docs/#/parsing/string-格式/

下面的代码应该适用于第二组数据

window.addEventListener('load', setup);
var formatDate = (dateString) => {
return moment(dateString, "MMM YYYY").toDate()
}
async function setup() {
var ctx = document.getElementById('myChart').getContext('2d');
var dollar = await getData();
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: dollar.years.map(year => formatDate(year)),
datasets: [{
label: 'Unemployment rate',
data: dollar.vals,
borderColor: 'rgb(153,222,101)',
backgroundColor: 'rgb(153,222,101, 0.2)',
pointRadius: 0,
borderWidth: 6,
pointHitRadius: 10,
}]
},
options: {
layout: {
padding: {
left: 0,
right: 15,
top: 0,
bottom: 0
}
},
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 3,
max: 8,
stepSize: 1
}
}],
xAxes: [{
type: "time",
time: {
unit: "year",
tooltipFormat: "YYYY"
},
gridLines: {
display: true,
drawOnChartArea: false,
},
ticks: {
display: true,
maxTicksLimit: 5,
maxRotation: 0,
minRotation: 0,
padding: 1
},
}],
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

在我的情况下,它不喜欢我的日期管道方法:

const date = '12/12/2021'.replace('/','-')
this.chartLabels.push(date)

不起作用,但起了作用

const transDate = new Date(it.asOfDate)
this.chatLabels.push(this.datePipe.transform(transDate, 'MM-dd-yyyy'))

最新更新