【问题标题】:Angular 2 ng2-charts doughnut text in the middle disappears on mouse hover中间的 Angular 2 ng2-charts 甜甜圈文本在鼠标悬停时消失
【发布时间】:2017-08-19 02:57:40
【问题描述】:

我已尝试在this 问题中发布的解决方案将文本放入圆环图的内部(在中间、垂直和水平对齐),它几乎可以完美运行。问题是每次鼠标悬停在图表上时,文本都会闪烁。似乎是因为当鼠标悬停在图表上时,再次调用了处理文本写入的函数。

我的组件代码是这样的:

imports ....

@Component({
    selector: 'my-component-app',
    templateUrl: '../views/my-component.component.html',
    styleUrls: ['../styles/my-component.component.css']
})

export class MyComponent implements OnInit {
    chartOptions;
    chartLabales;
    chartData;

    ngOnInit(): {
        this.chartData = ....
        this.chartOptions = ....
    }
}

关于如何解决这个问题的任何想法?谢谢

【问题讨论】:

    标签: angular chart.js ng2-charts


    【解决方案1】:

    你应该创建一个插件来绘制文本,而不是在动画完成上绘制它(这就是文本闪烁的原因,因为动画 onComplete 函数每次都会执行,当图表检测到任何用户交互时).

    ᴘʟᴜɢɪɴ

    Chart.plugins.register({
       afterDatasetsDraw: function(chart) {
          if (!chart.options.centerText) return;
          var ctx = chart.ctx,
             width = chart.canvas.width,
             height = chart.canvas.height;
          var fontSize = (height / 250).toFixed(2);
          ctx.font = fontSize + "em Verdana";
          ctx.textBaseline = "middle";
          ctx.fillStyle = "blue";
          var text = "Pass Rate 82%",
             textX = Math.round((width - ctx.measureText(text).width) / 2),
             textY = height / 2;
          ctx.fillText(text, textX, textY);
          ctx.restore();
       }
    });
    

    *文字绘制代码大多采用this答案。
    ngOnInit() 方法中添加这个插件,然后在您的图表选项中添加 - centerText: true

    另外,您需要在组件脚本的开头声明变量 Chart,如下所示:

    declare var Chart: any;
    

    【讨论】:

    • 知道了。该代码究竟应该放在哪里?在“@Component”符号之前?还是在我的组件的导出类中? '导出类 MyChartComponent 实现 OnInit { Chart.plugins.register(.....); a_property:a_type; }´
    • 我的意思是在您的组件脚本 (MyChart.component.ts) 中,在导入语句之前
    • 不!它通过 ChartJS 库在全球范围内可用。
    • 我收到 Cannot find name 'Chart' 错误。我的项目是使用Angular-CLI 构建的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多