Chartjs-ChartJS onclick fill area (Radar Chart)

1👍

There really is no specific chart.js API to do what you are wanting, but you can achieve the same results using the canvas API and a little geometry.

Basically, you want to increase the value if the user clicks outside the current value’s region, and you want to decrease if the user clicks inside the current value’s region.

I’ve modified your click handler to do just that.

function getElementPosition(obj) {
  var curleft = 0, curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
      return { x: curleft, y: curtop };
  }
  return undefined;
};

function getEventLocation(element,event){
  // Relies on the getElementPosition function.
  var pos = getElementPosition(element);

  return {
    x: (event.pageX - pos.x),
    y: (event.pageY - pos.y)
  };
};

function pointDistance(point1, point2) {
  return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
};

//Get the context of the Radar Chart canvas element we want to select
var ctx = document.getElementById("radarChart").getContext("2d");

// Create the Radar Chart
var myRadarChart = new Chart(ctx).Radar(radarData, radarOptions);

$("#radarChart").click(function (evt) {
  var eventLocation = getEventLocation(this,evt); 
  var activePoints = myRadarChart.getPointsAtEvent(evt);
  var eventLocDistToCenter = pointDistance({x: myRadarChart.scale.xCenter, y: myRadarChart.scale.yCenter}, eventLocation);
  var activePointDistToCenter = pointDistance({x: myRadarChart.scale.xCenter, y: myRadarChart.scale.yCenter}, activePoints[0]);

  if (eventLocDistToCenter < activePointDistToCenter) {
    activePoints[0].value--;
  } else {
    activePoints[0].value++;
  }

  myRadarChart.update();
});

Note, I also added a call to .update() so that the chart renders the change immediately. With the way you had it implemented, you would not see the chart change until the next render (i.e. when the mouse moves).

Here is a codepen forked from yours with the working solution. Click around to check it out.

Lastly, you probably want to think about upgrading to chart.js 2.0 (latest release is 2.5). 1.0 is long since unsupported and the latest version has LOTS of improvements. You should be able to easily port this over. Post a new question if you need help.

Leave a comment