基于模板预先创建图表对象

时间:2016-01-12 23:41:35

标签: highcharts

是否可以在使用模板定义图表的函数中包装highcharts图表,在渲染过程中传递图表数据然后将其渲染为div。基本上,我需要预先构建一个图表对象,并在特定时间将其渲染为div。

1 个答案:

答案 0 :(得分:1)

您可以准备全局json并使用merge()函数或直接将对象推送到模板。

    var template = {
    chart: {
      type: 'pie'
    },
    title: {
      text: ''
    },
    plotOptions: {
      pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
          enabled: true,
          format: '<b>{point.name}</b>: {point.percentage:.1f} %',
          style: {
            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
          }
        }
      }
    },
    series: [{
        data:[]
    }]
  };

    template.title.text = 'Pie chart 1';
  template.series[0].data = [['aaa1',3],['bbb1',4],['ccc1',5]];
  $('#container1').highcharts(template);

  template.title.text = 'Pie chart 2';
  template.series[0].data = [['aaa2',3],['bbb2',4],['ccc2',5]];
  $('#container2').highcharts(template);

简单演示:http://jsfiddle.net/80fsL5x5/

    var template = {
    chart: {
      type: 'pie'
    },
    title: {
      text: ''
    },
    plotOptions: {
      pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
          enabled: true,
          format: '<b>{point.name}</b>: {point.percentage:.1f} %',
          style: {
            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
          }
        }
      }
    },
    series: [{
        data:[]
    }]
  };

    var options1 = {
    title:{
        text: 'Pie chart 1'
    },
    series:[{
        data: [['aaa1',3],['bbb1',4],['ccc1',5]]
    }]
  };

  $('#container1').highcharts(Highcharts.merge(template,options1));

  var options2 = {
    title:{
        text: 'Pie chart 2'
    },
    series:[{
        data: [['aaa2',3],['bbb2',4],['ccc2',5]]
    }]
  };
  $('#container2').highcharts(Highcharts.merge(template,options2));

合并演示:http://jsfiddle.net/w46rm4vj/