【发布时间】:2020-05-17 06:20:10
【问题描述】:
我正在尝试在 d3.js 中制作显示美国所有县的 SVG 地图。当您单击某个状态时,它会将viewBox 转换为该状态并根据其在地球上的位置旋转它,因此它不会倾斜。
问题在于它渲染所有路径时非常慢。渲染 SVG 图形这么难有什么原因吗?有什么办法可以解决吗?
如果有人想偷看,我的代码就在这里:
<html>
<head>
<title>US Map</title>
<script src="http://d3js.org/d3.v5.min.js"></script>
<script src="https://d3js.org/topojson.v3.min.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
svg {
width: 100vw;
height: 100vh;
}
path {
fill: #ccc;
stroke: black;
stroke-width: .2;
}
#borders {
fill: none;
stroke-width: .8;
}
</style>
</head>
<body>
<svg></svg>
<script>
var svg = d3.select("svg"),
projection = d3.geoAlbersUsa(),
path = d3.geoPath(projection);
d3.json("https://cdn.jsdelivr.net/npm/us-atlas@3/counties-10m.json").then(function(us){
var states = topojson.feature(us, us.objects.states),
borders = topojson.mesh(us, us.objects.states, (a,b) => a != b);
states.features.filter(d => ![60,66,69,72,78].includes(Number(d.id))).forEach(function(state){
svg.datum(state)
.append("g")
.attr("id", state.id)
.on("click", function(d){
var p = projection.invert(path.centroid(d));
projection.rotate([-p[0], -p[1]]);
svg.transition().duration(750)
.selectAll("path:not(#borders)")
.attr("d", path);
var [[x0,y0],[x1,y1]] = path.bounds(d);
svg.transition().duration(750)
.attr("viewBox", `${x0-5} ${y0-5} ${x1-x0+10} ${y1-y0+10}`)
.select("#borders")
.attr("d", path(borders));
})
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features.filter(d => d.id.slice(0,2) == state.id))
.enter().append("path")
.attr("id", d => d.id)
.attr("d", path);
});
svg.append("path")
.attr("id", "borders")
.attr("d", path(borders));
var box = svg.node().getBBox();
svg.attr("viewBox", `${box.x} ${box.y} ${box.width} ${box.height}`);
projection = d3.geoMercator().scale([1000]);
path.projection(projection);
});
</script>
</body>
</html>```
【问题讨论】:
标签: javascript html d3.js svg topojson