本文介绍了如何在Chart.js v2.0的标签上添加OnClick事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

寻找在chartjs 2.0中的label元素上添加onClick句柄的方法
如果使用下面的方法,只要点击Char.js中的任何一个标签属性,就会在console.log中返回undifined V2.0 RadarChart。

  var data = {
//下面一行是标签
labels: [饮食,饮酒,睡觉,设计,编码,自行车,跑步],
数据集:[
{
label:My第一个数据集,//这只显示为图例,而不是标签。

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),
数据:[65,59,90,81 ,56,55,40]
},
....

  //以下是如何在chart.js V2中的图表点上点击,//但是,它不适用于标签,将返回未定义。 $('#ChartV2')。click(function(e){var activePoints = myRadarChart.getElementsAtEvent(e); var firstPoint = activePoints [0]; console.log(firstPoint); if(firstPoint!== undefined){alert (firstPoint._index);}});  


解决方案

getElementsAtEvent 只检查图表的主要元素(横条,点,扇区...)。如果您也想考虑使用标签,则必须重新实现标签的功能。



您需要的大部分代码已经可以通过Chart中的不同方法获得。 js库代码。只需复制粘贴/清除,如下所示。






脚本



您的点击hander应该是

$ $ $('#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 = [];
//遍历所有标签
helpers.each(myRadarChart.scale.ticks,function(label ,index){
for(var i = this.getValueCount() - 1; i> = 0; i--){
//这里我们有效地获得每个标签的边界框
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.defau ltFontSize);
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

//检查点击是否在边界框内
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);
}
});






小提琴 -


Looking For a method to add onClick handle on the "label" element in chartjs 2.0As using below method will return "undifined" in console.log whenever clicking on any one of the label attributes in Char.js V2.0 RadarChart.

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);
                }
 });

解决方案

getElementsAtEvent checks only the main elements of the chart (bars, points, sectors...). If you want to consider labels too, you'll have to reimplement the functionality for labels.

Most of the code you need is already available in different methods in the Chart.js library code. Just copy-paste / cleanup as done below.


Script

Your click hander should be

$('#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/

这篇关于如何在Chart.js v2.0的标签上添加OnClick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 21:10