Highchart dynamic creation - not rendering properl

2019-04-25 11:06发布

问题:

i am making a highchart drawing using dynamic function, it is not at all rending after the function called. later if i resize the window, it get rendering the data? any specific reason for this?

my function:

var chart;
$(document).ready(function(){

    function randomData(len){
        var arr = [];
        for(var i = 0; i<len;i++){
            arr.push(Math.random())
        }
        return arr;
    }

    var options = {
        chart:{
            renderTo:'graph',
            type:'line'
        },
        title:{
            text:null
        },
        xAxis: {
            plotBands: [{
                    from: 5,
                    to: 6,
                    color: 'yellow',
                    label: {
                            text: 'Yellow'
                    }
            }, {
                    from: 10,
                    to: 11,
                    color: 'green',
                    label: {
                            text: 'Green'
                    }
            }]
    },
        plotOptions:{
            series:{
                animation:false,
                dataLabels:{enabled:true,formatter:function(){return Highcharts.numberFormat(this.y)}}
            }
        }
    }

    chart = new Highcharts.Chart(options);
    var i = 1, s1,s2,s3,s4;

    function createChart(){
        s1 = chart.addSeries({data:randomData(20),name:'Line'+i},false);
    }

    $('#create').click(function(){  createChart() });

})

Pls check my jsfiddle.

http://jsfiddle.net/w46Sr/

回答1:

You need to add chart.redraw();

function createChart(){
    s1 = chart.addSeries({data:randomData(20),name:'Line'+i},false);
    chart.redraw();
}


回答2:

The problem is that you set the set parameter of addSeries as false.
In this case you have to set as true and it will redraw the chart after add the new serie.

For one serie.

chart.addSeries({data:randomData(20),name:'Line'+i},true);

Like the following example.
jsfiddle

Or if you want to add more than one serie in each click you just have to change one thing.

function createChart(seriesData){
    s1 = chart.addSeries(seriesData,false);
}

$('#create').click(function(){
    createChart(seriesData);
    chart.redraw();
});

You will add all of your series and after that redraw the chart, so you don't have to redraw your chart each time you add a new serie.