Tell if an line is hidden

空扰寡人 提交于 2019-12-24 07:49:14

问题


I have a chart that has multiple lines, each of which is plotted on it's own y-axis.

I have been trying to set it up so that when a line is hidden via the legend the axis it is on is hidden as well. My plan is to add a click listener to the canvas and from there disable or enable all axis depending on the line state.

My issue is determining if the line is hidden or not. The dataset.hidden property only seem to be relevant if the hidden value in the dataset._meta is undefined. I tried to set up code with this in mind:

ctx.onclick = function(){
    var changed = false;
    for(var j = 0;j < scatterChart.options.scales.yAxes.length;j++){
        var oldVal = scatterChart.options.scales.yAxes[j].display;
        var hidden = false;
        var isHiddenDataSet = scatterChart.data.datasets[j].hidden;

        if(isHiddenDataSet){
            hidden = true;
        }

        var isHiddenMeta = scatterChart.data.datasets[j]._meta[0].hidden;
        if(isHiddenMeta != null){
            hidden = isHiddenMeta;
        }

        scatterChart.options.scales.yAxes[j].display = !hidden;
        changed = changed || oldVal == scatterChart.options.scales.yAxes[j].display;
    }
    if(changed){
        scatterChart.update();
    }
}

This code worked for my original test that only have one chart but fails if there are more than one chart on the page as the index of the data object in _meta changes from chart to chart.

Is there a way to determine if a dataset is hidden?


回答1:


Since it works for you, I'm setting it as an answer

The _meta property in your datasets is very useful, especially when searching for specific properties such as hidden.
However it is quite difficult to handle it when there are several charts on the same page.

When doing the following :

var isHiddenMeta = scatterChart.data.datasets[j]._meta[0].hidden;

The 0 index is actually the first chart called in your code (index 1 is the second, etc..)
So you'll get the information of the first chart, and not the one you just clicked on.


To fix this, you need to use the Object.keys() method coupled with your dataset information, as follows :

var isHiddenMeta = scatterChart.data.datasets[j]._meta[Object.keys(scatterChart.data.datasets[j]._meta)[0]].hidden;

This will get you the hidden property of the dataset of the real chart.



来源:https://stackoverflow.com/questions/41877792/tell-if-an-line-is-hidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!