我有一些代码可以在 D3 中缩放和翻译 map ,但性能非常糟糕。缩放和平移时,刷新需要近 3 秒。我认为 map 会更好看,包括所有县的线边界,但在 6MB+ 时,我怀疑这可能是瓶颈的来源。是否有另一种方法可以处理转换,或者可能是优化 map 数据的方法? D3 真的不适合这种细节层次吗? D3 非常新。
我正在使用这里的形状文件,使用 QGIS 从 DBF 转换为 Geojson:
https://www.census.gov/cgi-bin/geo/shapefiles2010/main
<!doctype html>
<html>
<head>
<title>d3 map</title>
<script src="http://d3js.org/d3.v3.min.js">
</script>
</head>
<body>
<script>
var width = 800;
var height = 600;
var projection = d3.geo.mercator();
var path = d3.geo.path().projection (projection);
var canvas = d3.select ("body")
.append ("svg")
.attr ("width", width)
.attr ("height", height)
var zoomVar = d3.behavior.zoom()
.translate(projection.translate())
.scale(projection.scale())
.scaleExtent([height, 60 * height])
.on("zoom", onPostZoom);
var hotbox = canvas.append("g").call(zoomVar);
hotbox.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("fill", "white")
.attr("height", height);
d3.json ("cali.geojson", function (data)
{
hotbox.append("g")
.attr("id", "geometry")
.selectAll("path")
.data(data.features)
.enter()
.append("path")
.attr("d", path)
.attr("fill", "steelblue")
.on("click", onClick);
})
function onClick (d)
{
var centroid = path.centroid(d), translate = projection.translate();
projection.translate(
[translate[0] - centroid[0] + width / 2,
translate[1] - centroid[1] + height / 2 ]);
zoomVar.translate(projection.translate());
hotbox.selectAll("path").transition()
.duration(700)
.attr("d", path);
}
function onPostZoom()
{
projection.translate(d3.event.translate).scale(d3.event.scale);
hotbox.selectAll("path").attr("d", path);
}
</script>
</body>
</html>
最佳答案
您遇到的问题实际上并不是因为 D3,而是因为浏览器。主要瓶颈是渲染所有视觉元素,而不是计算它们的位置等。
避免这种情况的唯一方法是减少数据。一种开始方法是简化 QGIS 中的边界,例如使用dpsimplify 插件。
关于d3.js - D3JS 缩放和转换性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17888246/