[Chartjs]-Chart.js max legend height

5👍

I managed to do a stupid little hack to get exactly what I wanted, and it’s good enough for me, though it might be a little too hacky for other people’s tastes:

Chart.Legend.prototype.afterFit = function () {
    console.log('Before afterFit: ' + JSON.stringify(this.minSize) + ' ' + this.height);
    this.minSize.height = this.height = 100;
    console.log('After afterFit: ' + JSON.stringify(this.minSize) + ' ' + this.height);
}

console log is:

Before afterFit: {"width":1664,"height":527} 527
After afterFit: {"width":1664,"height":100} 100
Before afterFit: {"width":1664,"height":527} 527
After afterFit: {"width":1664,"height":100} 100

And the result:
Legend limited in height

I suppose to do this more cleanly, I should probably extend the Legend to override its afterFit behaviour. Will look into it, and I’ll update here if it’s possible to do it without too much hassle.

EDIT 19/10/2017:

Here is a “nicer” way to do this, which will look to a user like it was a built-in feature:

var origAfterFit = Chart.Legend.prototype.afterFit;
Chart.Legend.prototype.afterFit = function () {
    origAfterFit.call(this);
    if (this.options && this.options.maxSize) {
        var maxSize = this.options.maxSize;
        if (maxSize.height !== undefined) {
            this.height = Math.min(this.height, maxSize.height);
            this.minSize.height = Math.min(this.minSize.height, this.height);
        }
        if (maxSize.width !== undefined) {
            this.width = Math.min(this.width, maxSize.width);
            this.minSize.width = Math.min(this.minSize.width, this.width);
        }
    }
};

And example chart descriptor json:

{
    "type" : "line",
    "data" : {},
    "options" : {
        "legend" : {
            "position" : "bottom",
            "maxSize" : {
                "height" : 200
            },
            "labels" : {
                "usePointStyle" : true
            }
        }
    }
}

Leave a comment