实现d3点击缩放

Implement d3 Click-to-zoom

本文关键字:缩放 d3 实现      更新时间:2023-09-26

我不熟悉网络的东西,但即使我知道这是一个愚蠢的问题…我仍然不知道我做错了什么。网站上的代码:http://bl.ocks.org/mbostock/2206590看起来好像您可以将其复制并粘贴到html文档中,而只需修改指向美国的链接。Json以便它指向完整的文件路径。然而,代码只是打开一个空白页。对演示(http://bl.ocks.org/mbostock/raw/2206590/)上的页面源代码的检查与主页上提供的代码完全相同。我错过了什么来实现这个??谢谢! !

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.background {
  fill: none;
  pointer-events: all;
}
#states {
  fill: #aaa;
}
#states .active {
  fill: orange;
}
#state-borders {
  fill: none;
  stroke: #fff;
  stroke-width: 1.5px;
  stroke-linejoin: round;
  stroke-linecap: round;
  pointer-events: none;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960,
    height = 500,
    centered;
var projection = d3.geo.albersUsa()
    .scale(1070)
    .translate([width / 2, height / 2]);
var path = d3.geo.path()
    .projection(projection);
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);
svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", clicked);
var g = svg.append("g");
d3.json("/mbostock/raw/4090846/us.json", function(error, us) {
  if (error) throw error;
  g.append("g")
      .attr("id", "states")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
      .attr("d", path)
      .on("click", clicked);
  g.append("path")
      .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
      .attr("id", "state-borders")
      .attr("d", path);
});
function clicked(d) {
  var x, y, k;
  if (d && centered !== d) {
    var centroid = path.centroid(d);
    x = centroid[0];
    y = centroid[1];
    k = 4;
    centered = d;
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
  }
  g.selectAll("path")
      .classed("active", centered && function(d) { return d === centered; });
  g.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
      .style("stroke-width", 1.5 / k + "px");
}
</script>

下载us.json文件并将其放在与index.html相同的目录中。修改路径为us.json文件:

d3.json("us.json", function(error, us) {

这对我有用。如果您使用Chrome并在本地计算机上访问index.html文件,而不是从远程web服务器,则需要运行本地web服务器才能正常工作。如果你只是尝试在Chrome中打开index.html文件,由于Chrome的本地文件限制,它将无法正常显示。它需要通过web服务器访问。