Chart.js柱状图不呈现数据

wbrvyc0a  于 2024-01-07  发布在  Chart.js
关注(0)|答案(1)|浏览(266)

我正在尝试创建一个加密主页,跟踪和管理与比特币相关的数据。目前我正在使用blockchain.com API绘制一个图表,显示池中矿工的数量,该图表中没有列,只有一个空白的边框和轴。
我尝试使用以下代码渲染图形:

  1. tradeVolumeBTC()
  2. var columns = []
  3. const chartAPI = 'https://api.blockchain.info/pools?timespan=5days'
  4. document.onload = function getData() {
  5. fetch(chartAPI)
  6. .then(res => res.json())
  7. .then(toFindData => columns.push(toFindData['AntPool'], toFindData['BTC M4'], toFindData['Foundry USA'], toFindData['ViaBTC'], toFindData['Unknown'], toFindData['BTC.com'],
  8. toFindData['F2Pool'], toFindData['Binance Pool'], toFindData['Mara Pool'], toFindData['Poolin'], toFindData['SBI Crypto'], toFindData['Ultimus'], toFindData['Braiins Poo'],))
  9. }
  10. const ctx = document.getElementById('chart');
  11. new Chart(ctx, {
  12. type: 'bar',
  13. data: {
  14. labels: ['AntPool', 'BTC M4', 'Foundry USA', 'ViaBTC', 'Unknown', 'BTC.com', 'F2Pool', 'Binance Pool', 'Mara Pool', 'Poolin', 'SBI Crypto', 'Ultimus', 'Braiins Pool'],
  15. datasets: [{
  16. label: 'BTC Pools',
  17. data: columns,
  18. borderWidth: 1
  19. }]
  20. },
  21. options: {
  22. scales: {
  23. y: {
  24. beginAtZero: true
  25. }
  26. }
  27. }
  28. });

字符串
区块链API返回的数据为:

  1. {"ViaBTC":79,"Binance Pool":57,"Foundry USA":213,"F2Pool":85,"AntPool":194,"Mara Pool":32,"Poolin":12,"Unknown":29,"BTC M4":8,"SBI Crypto":13,"Ultimus":4,"BTC.com":4,"Braiins Pool":6}


而不是正确地呈现列的图形,而是不呈现,如图所示:


的数据

jvlzgdj9

jvlzgdj91#

渲染图表时columns为空。从API接收数据时渲染图表。我将回调函数中的render方法移动了。

  1. tradeVolumeBTC();
  2. var columns = [];
  3. const chartAPI = "https://api.blockchain.info/pools?timespan=5days";
  4. document.onload = function getData() {
  5. fetch(chartAPI)
  6. .then((res) => res.json())
  7. .then((toFindData) =>
  8. columns.push(
  9. toFindData["AntPool"],
  10. toFindData["BTC M4"],
  11. toFindData["Foundry USA"],
  12. toFindData["ViaBTC"],
  13. toFindData["Unknown"],
  14. toFindData["BTC.com"],
  15. toFindData["F2Pool"],
  16. toFindData["Binance Pool"],
  17. toFindData["Mara Pool"],
  18. toFindData["Poolin"],
  19. toFindData["SBI Crypto"],
  20. toFindData["Ultimus"],
  21. toFindData["Braiins Poo"]
  22. );
  23. const ctx = document.getElementById("chart");
  24. new Chart(ctx, {
  25. type: "bar",
  26. data: {
  27. labels: [
  28. "AntPool",
  29. "BTC M4",
  30. "Foundry USA",
  31. "ViaBTC",
  32. "Unknown",
  33. "BTC.com",
  34. "F2Pool",
  35. "Binance Pool",
  36. "Mara Pool",
  37. "Poolin",
  38. "SBI Crypto",
  39. "Ultimus",
  40. "Braiins Pool",
  41. ],
  42. datasets: [
  43. {
  44. label: "BTC Pools",
  45. data: columns,
  46. borderWidth: 1,
  47. },
  48. ],
  49. },
  50. options: {
  51. scales: {
  52. y: {
  53. beginAtZero: true,
  54. },
  55. },
  56. },
  57. });
  58. );
  59. };

字符串
了解有关Asychronous programming的更多信息

展开查看全部

相关问题