使用Json更新Chart.js


感谢您的阅读。我正在尝试通过甜甜圈图(来自Char.js(进行更新。以下是我的html代码的一部分。[Html]
<div class="homemainOne">
<canvas id="doughnutChart" height="250%"></canvas>
<div class="homePercentage">
<span class="homePercentageNum"></span>%
</div>
<button class="indexButton" id="">Click ME</button>
<span class="indexProduced" id="indexProduced"></span>
</div>

以下是我的js代码的一部分

const getDataFromSheet = async () => {
try {
const res = await axios.get('https://sheetdb.io/api/v1/pr969olea08op')
return res.data;
}
catch (e) {
console.log('error', e)
}
}
const produced = document.querySelector('.indexProduced');
const indexButton = document.querySelector('.indexButton');

const getProduced = async () => {
const PRO = await getDataFromSheet();
console.log(PRO[0].Val);
produced.innerText = Number(PRO[0].Val)
}
indexButton.addEventListener('click', getProduced);
var indexData = [Number(document.querySelector('.indexProduced').innerText), 720];
const chart1 = document.getElementById("doughnutChart");
const myChart = new Chart(chart1, {
type: 'doughnut',
data: {
labels: ["발전량", "총 소모량"],
datasets: [
{
label: "Population (millions)",
backgroundColor: ["rgb(58, 149, 231)", "rgba(58, 149, 231, 0.2"],
data: indexData
}
]
},
});

所以我想做的是

  1. 从API获取数据,每次单击按钮时在html上显示(更新(数据
  2. 使用显示的数据,通过"QuerySelect"获取,将其用作图表的数据

从API获取数据成功,也显示了数据。但问题是图表没有更新并显示初始值。

我这样做的原因是因为我不知道任何其他方法。如果有更好的方法从上面的API获取数据并将其更新为Chart,如果我能知道的话,那将是非常好的。感谢阅读!

我实际上并不清楚这个问题,但一旦我遇到这个问题,每次用户单击按钮时,我都必须更新图形数据。因此,我通常只从API获取数据,并将其放在我的图形js上,但有时它会显示,有时它不会显示,然后我通过删除图形div并再次附加它来解决这个问题,并在单击按钮后重新初始化图形。我不知道它是否解决了你的问题,但就我而言,它运行得很完美。我会给你一些我工作的样例代码这是我的HTML代码:

<div id="topModelGraph" class="height-400">
<canvas id="top-model"></canvas>
</div>

这是我的js代码:

$('div#topModelGraph').empty();
$('div#topModelGraph').append('<canvas id="top-model"></canvas>');
var ctx = document.getElementById('top-model');
var lineChart = new Chart(ctx, config);

在代码中,您似乎没有调用myChart.update()方法,该方法将在您单击按钮后更新并重新呈现图表。

最新更新