【问题标题】:Implement d3 Click-to-zoom实施 d3 点击缩放
【发布时间】:2016-11-13 01:31:01
【问题描述】:

我是网络新手,但即使我知道这是一个愚蠢的问题......我仍然无法弄清楚我做错了什么。网站上的代码:http://bl.ocks.org/mbostock/2206590 似乎您可以将其复制并粘贴到 html 文档中,只需修改指向 us.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>

【问题讨论】:

    标签: javascript html json d3.js


    【解决方案1】:

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

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

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

    希望这会有所帮助。

    【讨论】:

    • 不知道为什么这被否决了。如果您选择对某事投反对票,解释会很好。
    • 啊,一定是 Chrome 文件限制导致我出现问题。我没有考虑过,谢谢!我为你投了赞成票,但我的代表仍然低于 15 分。一旦我的代表上升,我会再试一次
    • 没问题。令人惊讶的是,有人会否决一个实际上对某人有帮助的答案。我将您的问题重新投票为零。感谢您接受答案!
    猜你喜欢
    • 1970-01-01
    • 2013-03-24
    • 2014-10-03
    • 2018-12-05
    • 2014-09-20
    • 1970-01-01
    • 2021-04-07
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多