如何使用 d3 创建响应式地图

gen*_*wip 5 d3.js

我正在尝试使我的地图具有响应性,因此会根据浏览器窗口大小调整其大小。这是我到目前为止,

样式文件

#mapbox {
border:2px solid #000;
width:960px;
height:550px;
background:#FFFFFF;
}
Run Code Online (Sandbox Code Playgroud)

即.js

var margin = {top: 10, left: 10, bottom: 10, right: 10},
width = parseInt(d3.select('#mapbox').style('width')), 
width = width - margin.left - margin.right, 
mapRatio = .5, 
height = width * mapRatio;
.
.
d3.select(window).on('resize', resize);
.
.
function resize(){  
    width = parseInt(d3.select('#mapbox').style('width'));
    width = width - margin.left - margin.right;
    height = width * mapRatio;


        projection.translate([width / 2, height / 2])
                .scale(width);

        svg.style('width', width + 'px')
            .style('height', height + 'px');

}
Run Code Online (Sandbox Code Playgroud)

当我调整窗口大小时,它仍然为我的 svg 容器保持相同的宽度和高度。我想那是因为,在调整大小功能中,我从 CSS 获取宽度和高度,无论我调整窗口大小是否正确?

我被困在这里,我错过了什么明显的东西吗?如果您有任何指示可以让我完成这项工作,那就太好了。

我几乎遵循以下示例

tom*_*tom 4

我将 svg 设置为响应式调整大小:

var svg = d3.select("body")
        .append("div")
        .attr("id", "svg")
        .append("svg")
        .attr("viewBox", "0 0 " + width + " " + height )
        .attr("preserveAspectRatio", "xMinYMin");
Run Code Online (Sandbox Code Playgroud)

然后像这样设置 css:

#svg {
    width:100%;
    height: auto;
}
Run Code Online (Sandbox Code Playgroud)