Chart.js没有显示在第二个选项卡上

时间:2017-03-17 20:20:40

标签: javascript jquery twitter-bootstrap-3 tabs chart.js

我有两个图表,一个条形图和一个我正在创建的折线图。条形图位于选项卡1上,而折线图位于第二个选项卡中。条形图工作正常,如果我将折线图指向选项卡1它工作正常。第二个选项卡未呈现。我相信这是因为隐藏的容器大小设置为0,并且单击第二个选项卡时图表没有呈现?我不确定如何纠正这个问题。以下是我认为相关的代码片段:

HTML

<div class="" role="tabpanel" data-example-id="togglable-tabs">

<ul id="myTab" class="nav nav-tabs bar_tabs" role="tablist">
  <li role="presentation" class="active"><a href="#tab_content1" id="bar-tab" role="tab" data-toggle="tab" aria-expanded="true"> Bar Chart</a></li>
  <li role="presentation" class=""><a href="#tab_contentL" role="tab" id="Line-tab" data-toggle="tab" aria-expanded="false"> Line Chart</a></li>
  <li role="presentation" class=""><a href="#tab_content2" role="tab" id="AMdata-tab" data-toggle="tab" aria-expanded="false"> Auto/Manual Data</a></li>
  <li role="presentation" class=""><a href="#tab_content3" role="tab" id="FTPRdata-tab" data-toggle="tab" aria-expanded="false"> FTPR Raw Data</a></li>
 </ul>

<div id="myTabContent" class="tab-content">
 <div role="tabpanel" class="tab-pane fade active in" id="tab_content1" aria-labelledby="bar-tab">                         
  <canvas id="mybarChart2" height="350"></canvas>           
 </div>

 <div role="tabpaneL" class="tab-pane fade" id="tab_contentL" aria-labelledby="Line-tab">                         
  <canvas id="myLineChart" height="350"></canvas>           
 </div>

JS

<script>
  $(document).ready(function() {
    var cb = function(start, end, label) {
      console.log(start.toISOString(), end.toISOString(), label);
      $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
    };

    var optionSet1 = {
      startDate: moment().startOf('month'),
      endDate: moment(),
      minDate: '01/01/2012',
      maxDate: '12/31/2020',
      /*dateLimit: {
        days: 60
      },*/
      showDropdowns: true,
      showWeekNumbers: true,
      timePicker: false,
      timePickerIncrement: 1,
      timePicker12Hour: true,
      ranges: {
        'Today': [moment(), moment()],
        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        //'Last 7 Days': [moment().subtract(6, 'days'), moment()],
        //'Last 30 Days': [moment().subtract(29, 'days'), moment()],
        'Month to Date': [moment().startOf('month'), moment()],
        //'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
        'Quarter to Date': [moment().startOf('quarter'), moment()],            
        'Year to Date': [moment().startOf('year'), moment()]
      },
      opens: 'left',
      buttonClasses: ['btn btn-default'],
      applyClass: 'btn-small btn-primary',
      cancelClass: 'btn-small',
      format: 'MM/DD/YYYY',
      separator: ' to ',
      locale: {
        applyLabel: 'Submit',
        cancelLabel: 'Clear',
        fromLabel: 'From',
        toLabel: 'To',
        customRangeLabel: 'Custom',
        daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
        monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        firstDay: 1
      }
    };
    $('#reportrange span').html(moment().startOf('month').format('MMMM D, YYYY') + ' - ' + moment().format('MMMM D, YYYY'));
    $('#reportrange').daterangepicker(optionSet1, cb);
    $('#reportrange').on('show.daterangepicker', function() {
      console.log("show event fired");
    });
    $('#reportrange').on('hide.daterangepicker', function() {
      console.log("hide event fired");
    });
    $('#reportrange').on('apply.daterangepicker', function(ev, picker) {
      console.log("apply event fired, start/end dates are " + picker.startDate.format('MMMM D, YYYY') + " to " + picker.endDate.format('MMMM D, YYYY'));
    });
    $('#reportrange').on('cancel.daterangepicker', function(ev, picker) {
      console.log("cancel event fired");
    });
    $('#options1').click(function() {
      $('#reportrange').data('daterangepicker').setOptions(optionSet1, cb);
    });
    $('#options2').click(function() {
      $('#reportrange').data('daterangepicker').setOptions(optionSet2, cb);
    });
    $('#destroy').click(function() {
      $('#reportrange').data('daterangepicker').remove();
    });

    $('#reportrange').on('apply.daterangepicker', function(ev, picker) {
      //console.log(picker.startDate.format('MMMM D, YYYY'));
      //dont need to do any changing of props here.
  //starting = picker.startDate.format('MM/DD/YYYY');
  console.log("Data changed. Reloading data...");
  myDataTable.ajax.reload();
  myDataTableFTPR.ajax.reload();
  myDataTableFTPRLoc.ajax.reload();
  loadFTPRChart(picker.startDate.format('MM/DD/YYYY'),picker.endDate.format('MM/DD/YYYY'));
  loadFTPRLine(picker.startDate.format('MM/DD/YYYY'),picker.endDate.format('MM/DD/YYYY'));
    });



Chart.defaults.global.maintainAspectRatio = false;

/*update chart instead of destroy and recreate */

// define a variable to store the chart instance (this must be outside of your function)
var myChart;

function loadFTPRChart(startdate, enddate) {
var BCData = {
labels: [],
datasets: [{
  label: "Pass %",
  backgroundColor: "rgba(83,106,127,1)",
  data: [],
  stack: 1
}, {
  label: "Fail %",
  backgroundColor: "rgba(83,106,127,.2)",
  data: [],
  stack: 1
}, {
  label: "Auto %",
  backgroundColor: "rgba(40,96,144,1)",
  data: [],
  stack: 2
}, {
  label: "Manual %",
  backgroundColor: "rgba(40,96,144,.2)",
  data: [],
  stack: 2
}]
};

$.getJSON("content/FTPR_AM_Graph_ajax.php", {
  startdate: startdate,
  enddate: enddate,
  location: "M"
})
.done(function(data) {
  console.log("data", data);
  $.each(data.aaData, function(key, val) {
    if (val == "") {
      return true
    }
    BCData.labels.push("Coater " + val[0]);
    BCData.datasets[0].data.push(parseFloat(val[2]));
    BCData.datasets[1].data.push(parseFloat(100 - val[2]));
    BCData.datasets[2].data.push(parseFloat(val[1]));
    BCData.datasets[3].data.push(parseFloat(100 - val[1]));
  });

  var option = {
    responsive: true,
  };
  console.log("BCData", BCData);

  // if the chart is not undefined (e.g. it has been created)
  // then just update the underlying labels and data for each
  // dataset and re-render the chart
  if (myChart) {
    myChart.data.labels = BCData.labels;
    myChart.data.datasets[0].data = BCData.datasets[0].data;
    myChart.data.datasets[1].data = BCData.datasets[1].data;
    myChart.data.datasets[2].data = BCData.datasets[2].data;
    myChart.data.datasets[3].data = BCData.datasets[3].data;
    myChart.update();
  } else {
    // otherwise, this is the first time we are loading so create the chart
    var ctx = document.getElementById("mybarChart2").getContext("2d");
    myChart = new Chart(ctx, {
      type: 'bar',
      data: BCData,
      options: {
        scales: {
          yAxes: [{
            ticks: {
              max: 100,
            },
            stacked: true,
          }]
        }
      }
    });
  }
});
}

loadFTPRChart($('#reportrange').data().daterangepicker.startDate.format('MM/DD/YYYY'), $('#reportrange').data().daterangepicker.endDate.format('MM/DD/YYYY'));    


var myLine;

function loadFTPRLine(startdate, enddate) {
var LCData = {
labels: [],
datasets: [{
  label: "FTPR Weekly",
  borderColor: "rgba(83,106,127,1)",
  data: [],
  stack: 1,
  fill: false,
  lineTension: .25,      
}]
};

$.getJSON("content/FTPRLine_ajax.php", {
  location: "M",
  startdate: startdate,
  enddate: enddate
})

.done(function(data) {
  console.log("data", data);
  $.each(data.aaData, function(key, val) {
    if (val == "") {
      return true
    }
    LCData.labels.push(val[0]);
    LCData.datasets[0].data.push(parseFloat(val[1]));        
  });

  var option = {
    responsive: true,
  };
  console.log("LCData", LCData);

  // if the chart is not undefined (e.g. it has been created)
  // then just update the underlying labels and data for each
  // dataset and re-render the chart
  if (myLine) {
    myLine.data.labels = LCData.labels;
    myLine.data.datasets[0].data = LCData.datasets[0].data;
    myLine.update();
  } else {
    // otherwise, this is the first time we are loading so create the chart
    var ctx = document.getElementById("myLineChart").getContext("2d");
    myLine = new Chart(ctx, {
      type: 'line',
      data: LCData,
      options: {
        scales: {
          yAxes: [{               
            stacked: false,
            ticks: {
              suggestedMin: 0
            }
          }],
          xAxes: [{             
            ticks: {
                autoSkip: true,
                maxTicksLimit: 20
              }
          }]
        }
      }
    });
  }
});

}

loadFTPRLine($('#reportrange').data().daterangepicker.startDate.format('MM/DD/YYYY'), $('#reportrange').data().daterangepicker.endDate.format('MM/DD/YYYY'));   

所以JS的第一部分是我的daterangepicker。第二个是条形图,第三个是折线图。我知道它正确地创建它们,因为如果我将折线图设置为“活动”选项卡,那么它可以正常工作,与条形图相同。我如何让他们同时工作?

由于

enter image description here

3 个答案:

答案 0 :(得分:1)

我使用maintainAspectRatio: false并通过在chartjs文档上应用注释来解决此问题。将画布放入具有样式尺寸属性的div容器中。

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
     <canvas id="chart"></canvas>
</div>

答案 1 :(得分:0)

您怀疑发生的事情是正确的。有两个选项可以解决这个问题(注意......选项2是最简单的)。

1)使用shown.bs.tab事件回调来创建其他图表,或者如果您之前在javascript中创建过,则可以将其称为.update()函数。

$('a[href="#pie"]').on('shown.bs.tab', function(){
  myPie.update();
});

2)将<canvas>元素放在标签中的<div>内。使用此方法,您根本不必使用选项卡事件。这是一个example来证明这一点。

答案 2 :(得分:0)

标记的答案对我不起作用,因为我使用maintainAspectRatio: false填充屏幕的整个高度。通过执行以下操作,我能够使其正常工作:

var currentWindowHeight = $(window).height()
var chartHeight = currentWindowHeight - 220

$("#my-tab").on("shown.bs.tab", function(){
    $("#mycanvasid").css("height", chartHeight);
});