使用 bootstrap

一種常用的方法是使用 bootstrap 的網格框架來定義圖表所在的區域。結合 clientWidth 變數和 window.onresize 事件,可以很容易地建立響應式 d3 SVG。

讓我們首先建立一個我們的圖表將被構建的行和列。

index.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-xs-12 col-lg-6" id="chartArea">
      </div>
    </div>
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.js"></script>
<script src="chart.js"></script>
</body>
</html>

這將建立一個在移動裝置上全屏的列和在大螢幕上的一半。

chart.js 之

var width = document.getElementById('chartArea').clientWidth;
//this allows us to collect the width of the div where the SVG will go.
var height = width / 3.236;
//I like to use the golden rectangle ratio if they work for my charts.

var svg = d3.select('#chartArea').append('svg');
//We add our svg to the div area

//We will build a basic function to handle window resizing.
function resize() {
    width = document.getElementById('chartArea').clientWidth;
    height = width / 3.236;
    d3.select('#chartArea svg')
      .attr('width', width)
      .attr('height', height);
}

window.onresize = resize;
//Call our resize function if the window size is changed.

這是一個極其簡化的示例,但確實涵蓋了如何設定圖表以響應的基本概念。調整大小函式將需要呼叫主更新函式,該函式將重繪所有路徑,軸和形狀,就像基礎資料已更新一樣。大多數關注響應式視覺化的 d3 使用者已經知道如何將更新事件構建為易於呼叫的函式,如介紹主題本主題所示