Chartjs 选项被忽略

时间:2021-06-22 19:44:29

标签: javascript chart.js

我试图在我的网站上使用一个简单的 ChartJS 图表,但所有选项都被忽略。因此,我的问题似乎与 this 类似,但据我所知,我在正确的位置提供了选项。

所以,这是(非常简单的)代码:

JS

let config01 = {
    type: 'doughnut',
    data: {
      labels: [
        'Part 01',
        'Part 02',
        'Part 03'
      ],
      datasets: [
        {
          data: [2000, 1000, 600],
          backgroundColor: [
            'rgb(0, 76, 138)',
            'rgb(50, 151, 230)',
            'rgb(250, 202, 55)',
          ],
          hoverOffset: 10
        }
      ]
    },
    options: {
      legend: {
        position: 'bottom',
        color: '#000000',
        labels: {
          usePointStyle: true,
        }
      },
      animation: {
        duration: 1000,
        easing: "linear"
      },
      title: {
        display: true,
        text: 'Some Title',
        fontColor: 'rgb(0, 18, 58)',
        fontSize: '18',
        padding: 5
      }
    }
  };
  
var ctx = document.getElementById('myChart-01').getContext('2d');
new Chart(ctx, config01);

HTML

 <body>
  <div>
    <canvas id="myChart-01" width="200px" height="200px"></canvas>
  </div>
 </body>

这将是一个有效的(没有应用选项)fiddle

2 个答案:

答案 0 :(得分:2)

legendtitle 应该在 options.plugins 中:

options: {
  plugins: {
    legend: {
      position: 'bottom',
      color: '#000000',
      labels: {
        usePointStyle: true,
      }
    },
    title: {
      display: true,
      text: 'Some Title',
      fontColor: 'rgb(0, 18, 58)',
      padding: 5,
      font: {
        size: '18'
      }
    }
  },
  animation: {
    duration: 1000,
    easing: "linear"
  }
}

答案 1 :(得分:2)

在每个文档部分定义的特定内容 (https://www.chartjs.org/docs/master/configuration/legend.html#configuration-options) 您可以看到命名空间,在其中您可以看到标题和图例必须在插件部分中配置,因为它们是内部插件,这也在迁移文档 (https://www.chartjs.org/docs/master/getting-started/v3-migration.html)

中说明

现场工作示例:

let config01 = {
  type: 'doughnut',
  data: {
    labels: [
      'Part 01',
      'Part 02',
      'Part 03'
    ],
    datasets: [{
      data: [2000, 1000, 600],
      backgroundColor: [
        'rgb(0, 76, 138)',
        'rgb(50, 151, 230)',
        'rgb(250, 202, 55)',
      ],
      hoverOffset: 10
    }]
  },
  options: {
    plugins: {
      legend: {
        position: 'bottom',
        color: '#000000',
        labels: {
          usePointStyle: true,
        }
      },
      title: {
        display: true,
        text: 'Some Title',
        font: {
          color: 'rgb(0, 18, 58)',
          size: 5
        },
      }
    },

    animation: {
      duration: 1000,
      easing: "linear"
    },

  }
};

var ctx = document.getElementById('myChart-01').getContext('2d');
new Chart(ctx, config01);
div {
  max-width: 200px;
  max-height: 200px;
}
<div>
  <canvas id="myChart-01" width="200px" height="200px"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.2/dist/chart.min.js"></script>
</div>