首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新Chart.js插件

更新Chart.js插件
EN

Stack Overflow用户
提问于 2018-04-02 07:24:52
回答 1查看 1.9K关注 0票数 3

是否可以使用chart.js插件更新chart.update()

我尝试过以下方法,但似乎插件没有更新

代码语言:javascript
复制
  let myChart;
  function drawChart(chart) {
    const ctx = document.getElementById("my-chart");
    if (!myChart) {
      myChart = new Chart(ctx, {
        type: 'scatter',
        data: chart.data,
        options: chart.option,
        plugins: chart.plugin
      });
    } else {
      myChart.data = chart.data;
      myChart.options = chart.option;
      myChart.plugins = chart.plugin;
      myChart.update();
   }
 }

任何想法都将不胜感激,谢谢。

EN

回答 1

Stack Overflow用户

发布于 2019-03-25 18:48:10

我还试着在更新图表之前重新提供插件,但没有被调用。因此,我对插件进行了修改,以接受调用更改图更新的@Input()组件变量。

请看我的例子--我必须在甜甜圈图的中间显示一个%。为此,我需要在afterDraw事件中调用一个插件。我做了两个改变:

  1. 我用箭头函数替换了插件中的函数关键字,这样我就可以使用this关键字来使用类变量。
  2. 然后,我在插件中使用了this.total,得到了我想要显示的%。因此,在图表更新过程中--我的新总计(总计是@Input()变量)将自动更新。
代码语言:javascript
复制
if (!this.doughnutChart && this.doughnut) {
    let ctx = this.doughnut.nativeElement.getContext("2d");
    if (ctx) {
        this.doughnutChart = new Chart(ctx, {
            // The type of chart we want to create
            type: 'doughnut',

            // The data for our dataset
            data: {
                labels: this.labels,
                datasets: [{
                    data: this.dataArray,
                    backgroundColor: this.colorsArray
                }]
            },

            // Configuration options go here
            options: this.chartOptions,

            // Plugin property will help to place total count
            // at the center of the doughnut after chart is rendered
            plugins: [{
                id: this.canvasId + '_plugin',
                afterDraw: (chart) => { // Using arrow function here
                    chart.ctx.fillStyle = 'black'
                    chart.ctx.textBaseline = 'middle'
                    chart.ctx.textAlign = 'center'
                    chart.ctx.font = '17px Verdana'
                    // Using this.total here
                    chart.ctx.fillText(this.total + '%',
                        chart.canvas.clientWidth / 2,
                        (chart.canvas.clientHeight / 2) + (titlePadding * 7 + 2 - bottomPadding))
                }
            }]
        });
    }
}
else if (this.doughnutChart) {
    // Update the chart
    this.doughnutChart.data.datasets[0].backgroundColor = this.colorsArray;                     
    this.doughnutChart.update();            
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49607020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档