Javascript 我的canvas onclick给我的结果来自错误的画布-如何确保正确的画布响应?

Javascript 我的canvas onclick给我的结果来自错误的画布-如何确保正确的画布响应?,javascript,canvas,chart.js,Javascript,Canvas,Chart.js,所以我有一张画布 <canvas style ="width: 30em; height:30em; overflow:visible;" id="GraphCanvas<?echo $this->id;?>"></canvas> 在onclick函数中,e.target将访问单击的元素。您正在使用var slice=ourChart.getElementAtEvent(e)那么看看你的getElementAtEvent函数,因为它返回的是最后一块画

所以我有一张画布

<canvas style ="width: 30em; height:30em; overflow:visible;"  id="GraphCanvas<?echo $this->id;?>"></canvas>

在onclick函数中,e.target将访问单击的元素。您正在使用
var slice=ourChart.getElementAtEvent(e)那么看看你的
getElementAtEvent
函数,因为它返回的是最后一块画布。诸如此类,遗憾的是,它不是我的,而是构建在chartjs中的东西。我要去窃听主人-谢谢!
    var ourChart = new Chart(ctx, {
      type: <?echo "'".$this->graphtype."'"?>,
      data: {
        labels: <?echo $arrParsed["labels"];?>, 
        keys: <?echo $arrParsed["keys"];?>,
        datasets: [{
          data:<?echo $arrParsed["data"];?>,
          backgroundColor: <?echo $arrParsed["color"]?>
        }]
      },
      options: {
        //Irrelevant graphics options
      }
    });
var canvas =  document.getElementById("GraphCanvas<?echo $this->id;?>");
canvas.onclick = function(e) {
      var slice = ourChart.getElementAtEvent(e);
        if(!slice.length) {
          return;
        }
        key = slice[0]._chart.config.data.keys[slice[0]._chart.config.data.labels.indexOf(slice[0]._model.label)]; //The array is indexed differently than the keys, and might be fubar, so we have to actually check the key at the same array index of the label we're looking at.  The key is the array index of the arrBuckets[] item in this graph!  EDIT: chartjs provides a _model that has the index, so you can just use that instead of fishing like I did.  Leaving this how it is because it works and for educational purposes


        console.log(slice);
        console.log(key);
        document.getElementById('bucketdrillid').value=key;
        //document.getElementById('graph<?echo $this->id;?>').submit();
}