使用 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 用户已经知道如何将更新事件构建为易于调用的函数,如介绍主题本主题所示