How to trigger hover programmatically in chartjs

前端 未结 1 416
轮回少年
轮回少年 2020-12-18 09:09

I want to set the hover effect in ChartJs programmatically i wish to see both effects hoverBorderWidth, and hoverBorderColor. I know how to activat

1条回答
  •  执笔经年
    2020-12-18 09:48

    Chart.js listens for mousemove events and checks if a datapoint is at the x/y coordinates. If so, it triggers the 'hover' behaviour for that point.

    Borrowing from the Chart.js tooltips test code, I wrote the snippet below to demonstrate accessing the correct properties and triggering an event.

    let c = new Chart($('#chart'), {
      type: 'doughnut',
      data: {
        labels: ['a', 'b', 'c', 'd'],
        datasets: [{
          data: [1, 2, 4, 8],
          backgroundColor: ['red', 'blue', 'green', 'orange']
        }]
      },
      options: {
        maintainAspectRatio: false
      }
    });
    $('#a').on('click', function() { t(0); });
    $('#b').on('click', function() { t(1); });
    $('#c').on('click', function() { t(2); });
    $('#d').on('click', function() { t(3); });
    
    function t(idx) {
      var meta = c.getDatasetMeta(0),
        rect = c.canvas.getBoundingClientRect(),
        point = meta.data[idx].getCenterPoint(),
        evt = new MouseEvent('mousemove', {
          clientX: rect.left + point.x,
          clientY: rect.top + point.y
        }),
        node = c.canvas;
      node.dispatchEvent(evt);
    }
    
    
    
    
    
    
    

    0 讨论(0)
提交回复
热议问题