简体   繁体   English

如何使谷歌日历图表移动响应?

[英]How to make Google Calendar chart Mobile responsive?

I am trying to plot top 50 days in the google calendar chart.我正在尝试 plot 谷歌日历图表中的前 50 天。 But when it comes to smaller screens like mobile some of the months are chopped off.但是当涉及到像移动设备这样的小屏幕时,有些月份就被砍掉了。

I cannot reduce my cell width as well.我也无法减小单元格宽度。 It will impact the view on bigger screens.它将影响更大屏幕上的视图。

Here is my html.这是我的 html。

<div id="calendar_basic" style = "width: 100%;"></div>

Here is my Java Script.这是我的 Java 脚本。

<script type="text/javascript">
      google.charts.load("current", {packages:["calendar"]});
      google.charts.setOnLoadCallback(drawChart);
      $(window).resize(drawChart);
   function drawChart() {
       var dataTable = new google.visualization.DataTable();
       dataTable.addColumn({ type: 'date', id: 'Date' });
       dataTable.addColumn({ type: 'number', id: 'Won/Loss' });
       dataTable.addRows([
          {% for n in cal_group %}
       [new Date({{n[0].strftime('%Y,%m,%d') }}),{{n[1]}}],

          {% endfor %}

        ]);

       var chart = new google.visualization.Calendar(document.getElementById('calendar_basic'));

       var options = {
         title: "Calendar Days and Count",
         height: 500,
         calendar: {
         yearLabel: {
        fontName: 'Times-Roman',
        fontSize: 32,
        color: '#1A8763',
        bold: true,
        italic: true
      },
      monthLabel: {
        fontName: 'Times-Roman',
        fontSize: 12,
        color: '#1A8763',
        bold: true,
        italic: true
      },
      monthOutlineColor: {
        stroke: '#1A8763',
        strokeOpacity: 0.8,
        strokeWidth: 1
      },
      unusedMonthOutlineColor: {
        stroke: '#9FE582',
        strokeOpacity: 0.8,
        strokeWidth: 1
      },
      underMonthSpace: 16,
    },
    colorAxis: {
        minValue: 0,
        colors: ['#99E37C','#40921F']
    },
    cellColor: {
        stroke: '#76a7fa',
        strokeOpacity: 0.5,
        strokeWidth: 1,
      },
      **width: $('#calendar_basic').width(),**
      forceIFrame: true,
       };

       chart.draw(dataTable, options);
   }
    </script>

I tried providing inline style element width 100%.我尝试提供 100% 的内联样式元素宽度。 It works for all other google charts like bar, column, pie, but not this calendar chart.它适用于所有其他谷歌图表,如条形图、柱形图、饼图,但不适用于这个日历图表。 I guess the default cell size of 16 is the culprit.我猜默认单元格大小为 16 是罪魁祸首。 But is there any option to make it responsive.但是是否有任何选项可以使其响应。

I managed to cobble together some kind of a solution that makes the calendar chart usable from desktop to mobile.我设法拼凑出某种解决方案,使日历图表可以从桌面使用到移动设备。

My solution adjusts the chart cell size depending on the screen size.我的解决方案根据屏幕大小调整图表单元格大小。 The cell size is set at a minimum of 12px after which the chart becomes hard to use - around the width of a tablet (screen size 768px).单元格大小设置为至少 12 像素,之后图表变得难以使用 - 大约是平板电脑的宽度(屏幕大小 768 像素)。 For mobiles I have implemented a scrolling div.对于手机,我实现了一个滚动 div。

HTML element that scrolls when the element is less than 690px wide: HTML 元素宽度小于 690px 时滚动的元素:

      <div style="overflow-x:scroll;overflow-y:hidden;max-width:100%;">
        <div id="chart_element" style="width:100%;min-width:690px;"></div>
      </div>

The calculation for cell size:单元格大小的计算:

       var chartElement = document.getElementById('chart_element');
       var cellSize = Math.max(12,((chartElement.offsetWidth*0.9)/52));

The code above gets the div containing the chart, calculates the width and divides it by the number of weeks in the year (52) to calculate how big the cell for the day should be.上面的代码获取包含图表的 div,计算宽度并将其除以一年中的周数 (52),以计算当天的单元格应该有多大。 The width is reduced to 90% to allow for margins.宽度减小到 90% 以留出边距。 If the cell size is less than 12, then use 12.如果像元大小小于 12,则使用 12。

To calculate the height of the chart is a bit tricky.计算图表的高度有点棘手。 Although we can use the calculated cell size to get a pretty good estimation of the height - if we fix the number of years displayed, the margins and headings can make things go a bit wonky.尽管我们可以使用计算出的像元大小来很好地估计高度 - 如果我们固定显示的年数,边距和标题会使 go 有点不稳定。

       var years = 2;
       var chartHeight = (cellSize*7*years) + (4*years*cellSize);

The above code calculates the height of year year using the cell size multiplied by 7 (rows) and then multiplied by the number of years displayed.上面的代码使用单元格大小乘以 7(行)然后乘以显示的年数来计算年份的高度。 It then adds some margins/paddings for headings etc using the cell size because it's about 3 cell blocks between the years and about one cell block above.然后它使用单元格大小为标题等添加一些边距/填充,因为它在年份之间大约有 3 个单元格块,而在上面大约有一个单元格块。

I wanted to get the actual height of the SVG after it was rendered and then force the chart div to that height, but the ready event returns before the chart is rendered.我想在渲染后获取 SVG 的实际高度,然后将图表 div 强制到该高度,但ready事件在图表渲染之前返回。

The last part of the solution is to re-draw the chart if the window size changes.解决方案的最后一部分是如果 window 大小发生变化,则重新绘制图表。 You can do that with this code:您可以使用以下代码执行此操作:

   window.addEventListener("resize", function() {
     drawChart();
   });

Finally, I decided to remove all settings that specify font size because I found the chart manages that better itself.最后,我决定删除所有指定字体大小的设置,因为我发现图表本身管理得更好。

Full code:完整代码:

  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
      google.charts.load("current", {packages:["calendar"]});
      google.charts.setOnLoadCallback(drawChart);

   function drawChart() {
       var dataTable = new google.visualization.DataTable();
       dataTable.addColumn({ type: 'date', id: 'Date' });
       dataTable.addColumn({ type: 'number', id: 'Feedback' });
       dataTable.addRows([
         [ new Date(2022, 1, 1), 0],
         [ new Date(2021, 1, 1), 0],
        // other dates ommitted for brevity
        ]);

       var chartElement = document.getElementById('chart_element');
       var chart = new google.visualization.Calendar(chartElement);
       var years = 2;
       var cellSize = Math.max(12,((chartElement.offsetWidth*0.9) / 52));
       var chartHeight = (cellSize*7*years) + (4*years*cellSize);

       var options = {
         title: "",
         height: chartHeight,
         calendar: {
          cellSize: cellSize,
          monthLabel: {
            fontName: 'Montserrat',
            color: '#4D4D4D',
            bold: false
          },
          monthOutlineColor: {
            stroke: '#4D4D4D',
            strokeOpacity: 1,
            strokeWidth: 1
          },
          unusedMonthOutlineColor: {
            stroke: '#CCCCCC',
            strokeOpacity: 0.8,
            strokeWidth: 1
          },
          yearLabel: {
            fontName: 'Montserrat',
            color: '#CCCCCC',
            bold: false,
            italic: false
          },
          focusedCellColor: {
            stroke: '#4D4D4D',
            strokeOpacity: 1,
            strokeWidth: 1
          }
         },
        noDataPattern: {
          backgroundColor: '#FFFFFF',
          color: '#F7EAD8'
        },
        colorAxis: {colors:['#aadbd3','#52817a']}
       };

       chart.draw(dataTable, options);

       google.visualization.events.addListener(chart, 'ready', new function() {
        // this is called before the chart is rendered unfortunately
       });
   }

   window.addEventListener("resize", function() {
     // this ensures that the chart gets redrawn when the screen is resized
     drawChart();
   });
  </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM