2016-05-04 26 views
5

Poszukuję metody dodawania uchwytów onClick na elemencie "label" w chartjs 2.0 Ponieważ użycie poniższej metody spowoduje zwrócenie "undifined" w console.log przy każdym kliknięciu dowolnego z atrybutów etykiety w Char.js V2.0 RadarChart .Jak dodać wydarzenie OnClick na etykietach w Chart.js v2.0?

var data = { 
    // below line is the labels 
    labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"], 
    datasets: [ 
     { 
      label: "My First dataset", //this only shows as legend, not label. 

      backgroundColor: "rgba(179,181,198,0.2)", 
      borderColor: "rgba(179,181,198,1)", 
      pointBackgroundColor: "rgba(179,181,198,1)", 
      pointBorderColor: "#fff", 
      pointHoverBackgroundColor: "#fff", 
      pointHoverBorderColor: "rgba(179,181,198,1)", 
      data: [65, 59, 90, 81, 56, 55, 40] 
     }, 
     .... 

//Below is how to OnClick on chart points in chart.js V2, 
 
//However, it didn't apply to labels, will return "undifined" . 
 
$('#ChartV2').click(function(e) { 
 
       var activePoints = myRadarChart.getElementsAtEvent(e);     
 
       var firstPoint = activePoints[0]; 
 
       console.log(firstPoint); 
 
       if (firstPoint !== undefined){ 
 
        alert(firstPoint._index);       
 
       } 
 
});

Odpowiedz

6

getElementsAtEvent sprawdza tylko główne elementy wykresu (bary, punkty, sektory ...). Jeśli chcesz również wziąć pod uwagę etykiety, musisz ponownie wdrożyć funkcjonalność etykiet.

Większość kodu, którego potrzebujesz, jest już dostępna w różnych metodach w kodzie biblioteki Chart.js. Po prostu skopiuj-wklej/wyczyść jak to zrobiono poniżej.


Script

Twoje kliknięcie zakręt powinien być

$('#myChart').click(function (e) { 
    var helpers = Chart.helpers; 

    var eventPosition = helpers.getRelativePosition(e, myRadarChart.chart); 
    var mouseX = eventPosition.x; 
    var mouseY = eventPosition.y; 

    var activePoints = []; 
    // loop through all the labels 
    helpers.each(myRadarChart.scale.ticks, function (label, index) { 
     for (var i = this.getValueCount() - 1; i >= 0; i--) { 
      // here we effectively get the bounding box for each label 
      var pointLabelPosition = this.getPointPosition(i, this.getDistanceFromCenterForValue(this.options.reverse ? this.min : this.max) + 5); 

      var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize); 
      var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle); 
      var pointLabeFontFamily = helpers.getValueOrDefault(this.options.pointLabels.fontFamily, Chart.defaults.global.defaultFontFamily); 
      var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily); 
      ctx.font = pointLabeFont; 

      var labelsCount = this.pointLabels.length, 
       halfLabelsCount = this.pointLabels.length/2, 
       quarterLabelsCount = halfLabelsCount/2, 
       upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount), 
       exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount); 
      var width = ctx.measureText(this.pointLabels[i]).width; 
      var height = pointLabelFontSize; 

      var x, y; 

      if (i === 0 || i === halfLabelsCount) 
       x = pointLabelPosition.x - width/2; 
      else if (i < halfLabelsCount) 
       x = pointLabelPosition.x; 
      else 
       x = pointLabelPosition.x - width; 

      if (exactQuarter) 
       y = pointLabelPosition.y - height/2; 
      else if (upperHalf) 
       y = pointLabelPosition.y - height; 
      else 
       y = pointLabelPosition.y 

      // check if the click was within the bounding box 
      if ((mouseY >= y && mouseY <= y + height) && (mouseX >= x && mouseX <= x + width)) 
       activePoints.push({ index: i, label: this.pointLabels[i] }); 
     } 
    }, myRadarChart.scale); 

    var firstPoint = activePoints[0]; 
    if (firstPoint !== undefined) { 
     alert(firstPoint.index + ': ' + firstPoint.label); 
    } 
}); 

Fiddle - http://jsfiddle.net/1Lngmtz7/

+0

Świetna lekcja z przykładem w skrzypcach. bardzo pomocne dla osób, które chcą rozszerzyć funkcje z oryginalnej wersji pliku chart.js, biorąc pod uwagę inne biblioteki wykresów, zamieszczam tutaj odniesienie z porównania lib tabeli według http://www.fusioncharts.com/javascript-charting-comparison/ , mówi: "Wykresy chart.js są rysowane za pomocą Canvas i dlatego nie mogą oferować żadnej interaktywności.", Twój przykład rozszerzył jego funkcjonalność i udowodnił, że jest nie tak. – BOBO

8

w chart.js 2,5 (być może nawet wcześniej) można umieścić onKliknij opcje:

'legend' : { 
    'onClick' : function (evt, item) { 
        console.log ('legend onClick', evt, item); 
       }, 
    'display' : true, 
    'labels' : ...