score:0

i found another way to preselect a segment, basically you can simulate a click event on the point. you can find in the dataset model the position x and y. here you can find my solution:

function simulateclick(x, y) {
  const clickevent = document.createevent('mouseevents');
  clickevent.initmouseevent('click', true, true, window, 0, 0, 0, x, y, 
  false, false, false, false, 0, null);
  document.elementfrompoint(x, y).dispatchevent(clickevent);
}

function initactivepoint(index) {
  const activepoint = mychart.data.datasets[0]._meta[0].data[index];
  simulateclick(activepoint._model.x, activepoint._model.y);
}

initactivepoint(0);

score:5

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.


Related Query

More Query from same tag