Chart.js 将标签变成链接

问题描述 投票:0回答:2

我不确定如果不执行以下操作是否可行:在 HTML 画布中创建链接,但让我们确定一下。

有没有一种方法(相对)简单地将 Chart.js 标签转换为链接?有问题的图表是雷达图:http://www.chartjs.org/docs/#radar-chart (到目前为止,我一直在使用图例,只需对库进行一些修改即可正常工作,但现在我应该使用标签本身。)

javascript chart.js
2个回答
1
投票

您可以监听单击事件,然后循环遍历所有 pointLabels 检查单击是否在该框中。如果是这种情况,您可以从包含所有标签的数组中获取相应的标签。

然后您可以使用

window.location = link
window.open(link)
打开链接。

点击在谷歌上搜索颜色的示例:

const options = {
  type: 'radar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'orange'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'pink'
      }
    ]
  },
  options: {
    onClick: (evt, activeEls, chart) => {
      const {
        x,
        y
      } = evt;
      let index = -1;

      for (let i = 0; i < chart.scales.r._pointLabelItems.length; i++) {
        const {
          bottom,
          top,
          left,
          right
        } = chart.scales.r._pointLabelItems[i];

        if (x >= left && x <= right && y >= top && y <= bottom) {
          index = i;
          break;
        }
      }

      if (index === -1) {
        return;
      }

      const clickedLabel = chart.scales.r._pointLabels[index];

      window.open(`https://www.google.com/search?q=color%20${clickedLabel}`); // Blocked in stack snipet. See fiddle
      console.log(clickedLabel)
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

小提琴:https://jsfiddle.net/Leelenaleee/fnqr4c7j/22/


0
投票

确实很晚了,但是 bencekd 对“Add Link to X-Label Chart.js”的回答对我有用。

我的项目使用旧的 Chart.js v1,它用于条形图,而不是雷达。您必须根据当前版本的 Chart.js 进行相应的修改。我不明白为什么它不适用于稍微重构的雷达。

代码(他们提供的Fiddle,我的一个小改动,“/*”的注释表示我的行):

var randomScalingFactor = function() {
    return Math.round(Math.random()*100)
};

var barChartData = {
    labels :
    ["January","February","March","April","May","June","July"],
    datasets : [
        {
            fillColor : "rgba(220,220,220,0.5)",
            strokeColor : "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        },
        {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,0.8)",
            highlightFill : "rgba(151,187,205,0.75)",
            highlightStroke : "rgba(151,187,205,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        }
    ]

}

var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
    responsive : true
});

$("#canvas").click(
    function(evt){
        var ctx = document.getElementById("canvas").getContext("2d");
        // from the endPoint we get the end of the bars area
        var base = myBar.scale.endPoint;
        var height = myBar.chart.height;
        var width = myBar.chart.width;
        // only call if event is under the xAxis
        if(evt.pageY > base){
            // how many xLabels we have
            var count = myBar.scale.valuesCount;
            var padding_left = myBar.scale.xScalePaddingLeft;
            var padding_right = myBar.scale.xScalePaddingRight;
            // calculate width for each label
            var xwidth = (width-padding_left-padding_right)/count;
            // determine what label were clicked on AND PUT IT INTO bar_index
            var bar_index = (evt.offsetX - padding_left) / xwidth;
            // don't call for padding areas
            if(bar_index > 0 & bar_index < count){
                bar_index = parseInt(bar_index);
                // either get label from barChartData
                //console.log("barChartData:" + barChartData.labels[bar_index]);
                // or from current data
                /* barChartData didn't work for me, so disabled above */
                var ret = [];
                for (var i = 0; i < myBar.datasets[0].bars.length; i++) {
                    ret.push(myBar.datasets[0].bars[i].label)
                };
                console.log("current data:" + ret[bar_index]);
                // based on the label you can call any function
                /* I made to go where I wanted here with a window.location.href
           and taking the label (ret[bar_index]) as an argument */
            }
        }
    }
);  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
    <div style="width: 50%">
            <canvas id="canvas" height="450" width="600"></canvas>
        </div>
    <div>
    Click on the x labels!
    </div>
    <div id="hello">
    </div>

© www.soinside.com 2019 - 2024. All rights reserved.