如何集成mustache模板读取json数据并在Chartjs中动态显示

wd2eg0qa  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(213)

我试图从data.json传递数据到mustache模板以创建条形图。我无法确定我需要在哪里传递数据以获得正确的图形。请查看以下代码片段来帮助我确定。

  1. <html>
  2. <body>
  3. <div>
  4. <canvas height="200px" width="300px" id="bar-graph"></canvas>
  5. </div>
  6. <script>
  7. const barCtx = document.getElementById('bar-graph').getContext('2d');
  8. new Chart(barCtx, barGraphConfig());
  9. function barGraphConfig() {
  10. return {
  11. type: 'bar',
  12. data: {
  13. datasets: [{
  14. data: {{barGraph}},
  15. borderRadius: 5,
  16. backgroundColor: [
  17. '#fece8c',
  18. '#a28cfe',
  19. '#a28cfe',
  20. '#feab8c',
  21. '#8ca2fe',
  22. '#8ca2fe',
  23. ],
  24. barThickness: 20
  25. }],
  26. labels: ['AAA', 'AA', 'A', 'BBB', 'BB', 'B']
  27. },
  28. options: {
  29. plugins: { legend: { display: false } },
  30. showTooltip: false,
  31. animation: {
  32. duration: 0,
  33. onComplete: renderDataLabel,
  34. },
  35. parsing: {
  36. xAxisKey: 'sector',
  37. yAxisKey: 'value'
  38. },
  39. scales: {
  40. x: {
  41. grid: {
  42. borderWidth: 3,
  43. borderColor: '#232323',
  44. display: false,
  45. },
  46. },
  47. y: {
  48. display: false,
  49. beginAtZero: true
  50. }
  51. }
  52. },
  53. };
  54. }
  55. </script>
  56. </body>
  57. </html>

数据.json

  1. barGraph: [
  2. {
  3. "name": "A",
  4. "value": 4
  5. },
  6. {
  7. "name": "AAA",
  8. "value": 10
  9. },
  10. {
  11. "name": "B",
  12. "value": 40
  13. },
  14. {
  15. "name": "BB",
  16. "value": 20
  17. },
  18. {
  19. "name": "BBB",
  20. "value": 7
  21. }
  22. ]

我们得到的错误

6fe3ivhb

6fe3ivhb1#

可以使用data.json得结构为dataset.data,但是为了使CHART.JS能够正确读取数据,需要在图表级设置options.parsing选项,如下所示:

  1. options: {
  2. parsing: {
  3. xAxisKey: 'name',
  4. yAxisKey: 'value'
  5. }
  6. }

参见CHART.JS文档:https://www.chartjs.org/docs/latest/general/data-structures.html#object-using-custom-properties
第一个

相关问题