Highcharts - set column width dynamically

2019-09-05 17:14发布

问题:

I want to create a column chart where the first column has 50% of the width of the second column. My idea was to read the width of the second column on the load-event, calculate the width and set it to the first column; the same for the redraw-event.

This works after when the chart is loaded for the first time, but I'm stuck when I want to change the column width in the redraw event: when resizing the window, I get the calculated column width of the "next to last" resize, and not the current one.

This fiddle shows the problem: http://jsfiddle.net/u8a0oo0d/

$(function () {
    $('#container').highcharts({
        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },
        chart: {
            events: {
                load: function () {
                    this.series[0].options.pointWidth = this.series[0].barW / 2;
                    this.series[0].update(this.series[0].options);
                },
                redraw: function(event) {
                    console.log('redraw', this.series[0]);
                    this.series[0].options.pointWidth = this.series[1].barW / 2;
                    this.series[0].isDirty = true;
                    //this.series[0].update(this.series[0].options);
                }
            }
        },
        series: [{
            type: 'column',
            //pointWidth: 10,
            data: [29.9, 71.5, 126.4, 149.2, 114.0, 126.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        },{
            data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
            type: 'column'
        }]
    });
});

回答1:

Your function is called after the redraw event is fired, so that's why you are getting the next to last width. Here's the DEMO for showing the timing of the function call.

The thing you can do is call the redraw again in that function except for just that particular serie, which doesn't call the same handler and cause a loop. Here's what you can do:

redraw: function(event) {
            this.series[0].options.pointWidth = this.series[1].barW / 2;
            this.series[0].redraw();
        }

And here's the working fiddle.



标签: highcharts