skip to Main Content

I know that I can change the width of the line and its points with borderWidth: 1, pointRadius: 1, it works fine.

But how to increase the width of the line and its points when hovering the mouse cursor over a line?
I tried hoverBorderWidth: 2, hoverRadius: 2 as suggested in the docs but with no success.

I tested in Google Apps Script by adding these lines to the html file:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-autocolors"></script>

2

Answers


  1. Your code is almost right, but you are forgetting to add Chart.js datalables plugin which is essential for using hoverBorderWidth or hoverRadius.

    Include

    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
    
    Login or Signup to reply.
  2. HTML

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
    
    <canvas id="myChart"></canvas>
    

    JS

    const ctx = document.getElementById('myChart').getContext('2d');
    
    // Create the chart with the plugin and other options
    const chart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['Label 1', 'Label 2', 'Label 3'],
        datasets: [{
          label: 'Data',
          data: [10, 20, 30],
          backgroundColor: 'rgba(0, 123, 255, 0.5)'
        }]
      },
      options: {
        plugins: {
          datalabels: {
            display: false // Hide the data labels by default
          }
        },
        responsive: true,
        maintainAspectRatio: false,
        hover: {
          onHover: handleHover // Call the handleHover function on hover
        }
      }
    });
    
    // Function to handle the hover effect
    function handleHover(activeElements) {
      if (activeElements.length > 0) {
        const element = activeElements[0];
        
        // Increase border radius and width
        element._model.borderWidth += 2;
        element._model.borderRadius = 10;
        
        // Display the data labels
        chart.options.plugins.datalabels.display = true;
        
        chart.update();
      } else {
        // Reset styles and hide data labels when not hovering
        chart.data.datasets[0].data.forEach((_, index) => {
          const element = chart.getDatasetMeta(0).data[index];
          
          element._model.borderWidth = 0;
          element._model.borderRadius = 0;
        });
        
        chart.options.plugins.datalabels.display = false;
        
        chart.update();
      }
    }
    

    Let me know if it’s working my friend

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search