如何使 Canvas JS 图表在选项卡中响应?

How to make Canvas JS chart responsive in tab?

您好,我有两个 bootstrap 选项卡,在第二个选项卡中我显示 canvas js 折线图。在 canvas js 图表本身设置高度和宽度之前,图表不会覆盖整个屏幕,这会破坏响应。图表中显示的图表没有高度和宽度:-

选项卡代码:-

<div class="tabbable">
    <ul class="nav nav-tabs">
        <li class="active"><a href="#s1" data-toggle="tab">Tab 1</a></li>
        <li><a href="#s2" data-toggle="tab">Tab 2</a></li>
    </ul>

    <div class="panel panel-flat">
        <div class="panel-body">
           <div class="tab-content">
               <div class="tab-pane" id="s1">
                   <div class="row">
                       <div class="col-md-12">
                             A table is shown in first tab  
                       </div>
                   <div>                       
                </div>

                <div class="tab-pane" id="s2">
                    <div class="row">
                        <div class="col-md-12">
                            <div id="chartContainer" style="height: 365px !important; width: 100% !important;"></div>  
                        </div>
                    <div>                       
                </div>
           </div>
        <div>                       
     </div>
  </div>

图表的javascript:-

<script type="text/javascript">
window.onload = function () {

    var chart = new CanvasJS.Chart("chartContainer",
    {

        title:{

        },
        animationEnabled: true,
        axisX:{

            gridColor: "Silver",
            tickColor: "silver",
           interval: 1

        },                        
                    toolTip:{
                      shared:true
                    },
        theme: "theme2",
        axisY: {
            gridColor: "Silver",
            tickColor: "silver"
        },
        legend:{
            verticalAlign: "center",
            horizontalAlign: "right"
        },

        data: [
        {        
            type: "line",
            markerType: "square",
            color: "#F08080",
            dataPoints: [
            { x: 1, y: 6.7 },
            { x: 2, y: 8.0 },
            { x: 3, y: 7.10 },
            { x: 4, y: 8.58 },
            { x: 5, y: 9.34 },
            { x: 6, y: 6.63 },
            { x: 7, y:7.47 },
            { x: 8, y: 8.53 },

            ]
        }
        ],
        });

      chart.render();
        }
    </script>

如果有人可以帮助我在不设置图表本身的高度和宽度的情况下使图表在选项卡中以全宽显示,我将不胜感激。非常感谢任何帮助。

CanvasJS Chart 会根据容器的尺寸自动设置图表的高度和宽度。如果没有为容器设置值,它将采用默认值。

在bootstrap中,由于第二个选项卡一开始没有显示,所以图表采用默认值。要解决此问题,应在 shown.bs.tab 事件被 bootstrap 触发时呈现第二个图表。

$('#bs-tab2').on("shown.bs.tab",function(){
  chartTab2();
  $('#bs-tab2').off(); // to remove the binded event after the initial rendering
});

检查此 jsfiddle