Set custom legend item symbol (or icon) in HIghcha

2019-02-25 18:07发布

问题:

I'm trying to change the default highcharts legend symbol to my own custom one. I wish to have a font-awesome icon next to the legend label. for that, Iv'e thought about labelformatter:

labelFormatter: function () {
                    var on  = '<g><text x="0" y="0" style="color:'+this.color+';font-family:FontAwesome">&#xf14a;</text></g> ' + this.name;
                    var off   = '<g><text x="0" y="0" style="color:'+this.color+';font-family:FontAwesome">&#xf0c8;</text></g> ' + this.name;

                    return  this.iconState ? on : off;
                }

that actually let me add the icon as I wanted, but now my probelm is the following: when clicking on the legend items, the icons remain in the original color and do not become gray like the labels. Iv'e thought about re-rendering the legend when a click event is fired (using legendItemClicked), but I havnn't found anything that works out.

Does anyone know how can I manage re-rendering the legend?

OR

How Its even possible to set the symbol to my own?

Thanks!

回答1:

You can define your custom symbol by adding this information to Highcharts symbol arrays, like in the example:

 Highcharts.SVGRenderer.prototype.symbols.cross = function (x, y, w, h) {
    return ['M', x, y, 'L', x + w, y, 'z'];
};
if (Highcharts.VMLRenderer) {
    Highcharts.VMLRenderer.prototype.symbols.cross = Highcharts.SVGRenderer.prototype.symbols.cross;
}

http://jsfiddle.net/nhx59/2/

or use a image http://www.highcharts.com/demo/spline-symbols



回答2:

There is another way. In my labelFormatter, i return a html string which includes my image, with a unique class name or id.

Now, I listen for legendItemClick event under plotOptions.column.events or plotOptions.line.events and then find my element and add a css class which has opacity in it like below:.dullImage { opacity: 0.4; filter: alpha(opacity=40); /* msie */ }

In the legendItemClick, event object is passed and you can look at event.currentTarget.name (to find legend name) and event.currentTarget.isDirty to determine if this was click to disable or enable legend.