问题
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.
Thanks in advance!
回答1:
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.
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.
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();
You just need to define what segment you want to highlight and store it in a var called segmentIndexToHihlight
and it should work.
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.
来源:https://stackoverflow.com/questions/42816185/chart-js-set-active-segment-on-initialize