Chart.js在初始化时设置活动细分 [英] Chart.js set active segment on initialize

查看:67
本文介绍了Chart.js在初始化时设置活动细分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用chart.js v2,并且尝试在加载图表时模拟甜甜圈图上的线段的悬停状态,因此似乎突出显示了一个部分。

I'm working with chart.js v2 and I am trying simulate the hover state of a segment on a doughnut graph when the chart loads so it appears there is a section alright highlighted.

我已经搜索和梳理了一天的代码,却找不到解决此问题的好方法。

I've been searching and combing the code for a day now and can't figure out a good way to do this.

谢谢!

推荐答案

设置细分的悬停样式有点令人困惑,因为它的确未在任何地方记录。不过,当我想突出显示图例标签悬停的片段时,我还是能够弄清楚这一点。

Setting a segment's hover style is a bit confusing because its not really documented anywhere. Nevertheless, I was able to figure it out a while back when I wanted to highlight a segment when it's legend label was hovered.

为此,您需要使用饼图 .updateHoverStyle()原型方法,并传入要突出显示的细分。图表分段存储在数组的 _meta 对象中,其中每个分段索引均与图表数据数组中每个值的位置匹配。

To do this, you need to use the pie chart .updateHoverStyle() prototype method and pass in the segment you want highlighted. The chart segments are stored in the _meta object in an array where each segment index matches the position of each value in your chart's data array.

这里是一个示例(假设您的图表实例存储在名为 myPie 的变量中。

Here is an example (assuming your chart instance is stored in a var called myPie.

// get the segment we want to highlight
var activeSegment = myPie.data.datasets[0]._meta[0].data[segmentIndexToHihlight];

// update the hover style
myPie.updateHoverStyle([activeSegment], null, true);

// render so we can see it
myPie.render(); 

您只需要定义要突出显示的段并将其存储在名为 segmentIndexToHihlight ,它应该可以工作。

You just need to define what segment you want to highlight and store it in a var called segmentIndexToHihlight and it should work.

这里是 codepen示例对此进行了说明。请注意,我故意不突出显示正在加载的代码段(我等待3秒钟),以便您可以看到更改发生了。

Here is a codepen example demonstrating this. Note, I purposely did not highlight the segment on load (I wait 3 seconds) so that you can see the change occur.

这篇关于Chart.js在初始化时设置活动细分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆