如何访问图表.js默认设置?(相关 - 如何打开工具提示?

How do I access Chart.js default settings? (& related -- how do I turn the tool tips on?)

本文关键字:设置 相关 工具提示 何打开 默认 何访问 访问 js      更新时间:2023-09-26

我正在使用图表.js甜甜圈图。图表显示正常。但是,它缺少工具提示(就像我使用Chart.js制作的所有其他图表一样)。为什么会这样,我该如何打开它们?在线文档声称我可以在 Chart.defaults.global 访问全局默认值(其中工具提示可以设置为打开/关闭,尽管该站点声称它们默认为打开),这对我不起作用,因为 Chart.defaults 甚至不存在。我正在尝试访问这些默认值,以便可以打开工具提示。感谢您提供的任何帮助。

    var context = document.getElementById("scoreChart").getContext("2d");
    var chartData = [
        {
            label: "Number correct",
            value: $scope.numRight,
            color: "rgb(134, 202,54)",
            highlight: "rgb(100,100,100)"
            //not sure what highlight does
        },
        {
            label: "Number wrong",
            value: $scope.myTest.testQuestions.length - $scope.numRight,
            color: '#7c0b10',
            highlight: 'rgb(10,10,10)'
        }
    ];
    var theChart = new Chart(context);
    var theDough = theChart.Doughnut(chartData/*, chartOptions*/);
    console.log("Here is the chart object:");
    console.log(theChart);
    console.log("Chart.Doughnut object:");
    console.log(theChart.Doughnut);
    console.log("Chart.Doughnut.defaults:");
    console.log(theChart.Doughnut.defaults); // <-- This works
    console.log("theChart.defaults:");
    console.log(theChart.defaults); // <--This is undefined
    console.log("Chart.defaults.global:");
    console.log(Chart.defaults.global); // throws an error 
                        // because Chart.defaults is undefined

更新:修复了它。Chart.js的bower版本非常古老。请参阅下面的答案。

我使用Bower下载了Chart.js。Chart.js在Bower上列出的版本是旧的。这就是文档错误的原因。我不得不将最新的图表.js从Github剪切并粘贴到我的项目中。瞧,工具提示和对象的行为与文档所说的一样。或者,正如JAAulde指出的那样,您可以更轻松地将bower依赖项设置为指向:

  "chartjs": "master"

这应该会自动拉取正确的副本。

theCharttheDough应该一次性设置,而不是作为单独的对象。例如:

var theChart = new Chart(ctx).Doughnut(data);

如果这仍然无法获得工具提示,请传入并修改以下选项:

var theChart = new Chart(ctx).Doughnut(data, {
     // Boolean - Determines whether to draw tooltips on the canvas or not
     showTooltips: true,
});

有关工具提示样式的更多变化,请查看此页面上的全局图表选项文档:http://www.chartjs.org/docs/#getting-started-global-chart-configuration