如何向 d3 可折叠树示例添加缩放功能?

2023-12-08

我正在尝试向 d3 可折叠树添加缩放功能example,但无法让它工作。我知道有人对此有疑问here尽管看起来相当彻底,但我的更改不起作用。我得到的唯一东西是一张白页。可能与我对 javascript/d3 相当陌生这一事实有关。这是我的代码。

<!DOCTYPE html>
<meta charset="utf-8">
<style>

svg {
    pointer-events: all;
}

.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1.5px;
}

tree {
pointer-events: all;
}

.node text {
  font: 12px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 1.5px;
}



</style>
<body>
<script src="d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 120, bottom: 20, left: 120},
    width = 1500 - margin.right - margin.left,
    height = 800 - margin.top - margin.bottom;

var i = 0,
    duration = 750,
    root;

var tree = d3.layout.tree()
    .size([height, width]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

d3.json("flare.json", function(error, flare) {
  root = flare;
  root.x0 = height / 2;
  root.y0 = 0;

  function collapse(d) {
    if (d.children) {
      d._children = d.children;
      d._children.forEach(collapse);
      d.children = null;
    }
  }

  root.children.forEach(collapse);
  update(root);
});

d3.select(self.frameElement).style("height", "800px");

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
      links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) { d.y = d.depth * 180; });

  // Update the nodes…
  var node = svg.selectAll("g.node")
      .data(nodes, function(d) { return d.id || (d.id = ++i); });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .on("click", click);

  nodeEnter.append("circle")
      .attr("r", 1e-6)
      .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

  nodeEnter.append("text")
      .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
      .text(function(d) { return d.name; })
      .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

  nodeUpdate.select("circle")
      .attr("r", 4.5)
      .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

  nodeUpdate.select("text")
      .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
      .remove();

  nodeExit.select("circle")
      .attr("r", 1e-6);

  nodeExit.select("text")
      .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
      .data(links, function(d) { return d.target.id; });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      });

  // Transition links to their new position.
  link.transition()
      .duration(duration)
      .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {x: source.x, y: source.y};
        return diagonal({source: o, target: o});
      })
      .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });

    d3.select("svg")
    .call(d3.behavior.zoom()
          .scaleExtent([0.5, 5])
          .on("zoom", zoom));


}

// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);


function zoom() {
    var scale = d3.event.scale,
        translation = d3.event.translate,
        tbound = -h * scale,
        bbound = h * scale,
        lbound = (-w + m[1]) * scale,
        rbound = (w - m[3]) * scale;
    // limit translation to thresholds
    translation = [
        Math.max(Math.min(translation[0], rbound), lbound),
        Math.max(Math.min(translation[1], bbound), tbound)
    ];
    d3.select(".drawarea")
        .attr("transform", "translate(" + translation + ")" +
              " scale(" + scale + ")");
}




}

</script>

为什么缩放实现不起作用?


我稍微研究了一下你的代码,发现了几个潜在的问题:

根据您运行此程序的位置/方式,加载flare.json 文件可能会导致 CORS 错误(例如,如果您尝试链接到 bostock 的 github 上的文件)。您可以将 json 对象直接嵌入到“flare”变量中,然后只需将 d3.json() 方法中的代码移动到脚本底部,并将根变量分配给flare。

var flare =  ...paste contents of flare.json here... ;

您的 javascript 方法是按照在定义方法之前引用方法的顺序定义的(您应该将缩放和单击方法移到更新方法之前):

collapse(d){...}
zoom(){...}
click(){...}
update(){...}

您的缩放方法引用了“h”、“w”和“m”,它们在任何地方都没有定义。我认为它们应该是宽度、高度和边距:

var zoom = function() {
    var scale = d3.event.scale,
        translation = d3.event.translate,
        tbound = -height * scale,
        bbound = height * scale,
        lbound = (-width + margin.right) * scale,
        rbound = (width - margin.left) * scale;

最后,要修复缩放问题,您应该像这样修复缩放方法:

var zoom = function() {
    var scale = d3.event.scale,
        translation = d3.event.translate,
        tbound = -height * scale,
        bbound = height * scale,
        lbound = (-width + margin.right) * scale,
        rbound = (width - margin.left) * scale;
    // limit translation to thresholds
    translation = [
        Math.max(Math.min(translation[0], rbound), lbound),
        Math.max(Math.min(translation[1], bbound), tbound)
    ];
    svg.attr("transform", "translate(" + translation + ")" + " scale(" + scale + ")");
}

请注意,我将“select(”.drawArea”)”替换为“svg”。因为您想要转换顶部的 g 元素(即“svg”变量中的内容)。

仅供参考 - 我无法真正在 plnkr 或 jsFiddle 中实现此功能,因为由于 plnkr 和 jsFiddle 中处理变量/函数作用域的方式,存在奇怪的 d3 错误(请参阅here)。这可能是其他人可以解决的问题。但这是完整的代码(减去嵌入的flare.json变量)。我在自己的 Tomcat 容器中运行了这段代码,可以双击树并将其放大。您可能想要尝试缩放和平移,以便树不会绘制在可见窗口的边界之外(现在)如果双击它会缩放,但会居中,因此树的左侧不在浏览器窗口的一侧)。

<!DOCTYPE html>
<meta charset="utf-8">
<style>

svg {  pointer-events: all;  }
.node { cursor: pointer;  }
.node circle {
    fill: #fff;
    stroke: steelblue;
    stroke-width: 1.5px;
}
tree {  pointer-events: all;  }
.node text {  font: 12px sans-serif;  }
.link {
    fill: none;
    stroke: #ccc;
    stroke-width: 1.5px;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 120, bottom: 20, left: 120},
    width = 1500 - margin.right - margin.left,
    height = 800 - margin.top - margin.bottom;

var i = 0,
    duration = 750,
    root;

var tree = d3.layout.tree()
    .size([height, width]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

d3.select(self.frameElement).style("height", "800px");

var collapse = function(d) {
    if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = null;
    }
}

var zoom = function() {
    var scale = d3.event.scale,
        translation = d3.event.translate,
        tbound = -height * scale,
        bbound = height * scale,
        lbound = (-width + margin.right) * scale,
        rbound = (width - margin.left) * scale;
    // limit translation to thresholds
    translation = [
        Math.max(Math.min(translation[0], rbound), lbound),
        Math.max(Math.min(translation[1], bbound), tbound)
    ];
    svg.attr("transform", "translate(" + translation + ")" + " scale(" + scale + ")");
}

// Toggle children on click.
var click = function(d) {
    if (d.children) {
        d._children = d.children;
        d.children = null;
    } else {
        d.children = d._children;
        d._children = null;
    }
    update(d);
};

var update = function(source) {
    // Compute the new tree layout.
    var nodes = tree.nodes(root).reverse(),
        links = tree.links(nodes);

    // Normalize for fixed-depth.
    nodes.forEach(function(d) { d.y = d.depth * 180; });

    // Update the nodes…
    var node = svg.selectAll("g.node")
        .data(nodes, function(d) { return d.id || (d.id = ++i); });

    // Enter any new nodes at the parent's previous position.
    var nodeEnter = node.enter().append("g")
        .attr("class", "node")
        .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
        .on("click", click);

    nodeEnter.append("circle")
        .attr("r", 1e-6)
        .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

    nodeEnter.append("text")
        .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
        .attr("dy", ".35em")
        .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
        .text(function(d) { return d.name; })
        .style("fill-opacity", 1e-6);

    // Transition nodes to their new position.
    var nodeUpdate = node.transition()
        .duration(duration)
        .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

    nodeUpdate.select("circle")
        .attr("r", 4.5)
        .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

    nodeUpdate.select("text")
        .style("fill-opacity", 1);

    // Transition exiting nodes to the parent's new position.
    var nodeExit = node.exit().transition()
        .duration(duration)
        .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
        .remove();

    nodeExit.select("circle")
        .attr("r", 1e-6);

    nodeExit.select("text")
        .style("fill-opacity", 1e-6);

    // Update the links…
    var link = svg.selectAll("path.link")
        .data(links, function(d) { return d.target.id; });

    // Enter any new links at the parent's previous position.
    link.enter().insert("path", "g")
        .attr("class", "link")
        .attr("d", function(d) {
            var o = {x: source.x0, y: source.y0};
            return diagonal({source: o, target: o});
         });

    // Transition links to their new position.
    link.transition()
        .duration(duration)
        .attr("d", diagonal);

    // Transition exiting nodes to the parent's new position.
    link.exit().transition()
        .duration(duration)
        .attr("d", function(d) {
            var o = {x: source.x, y: source.y};
            return diagonal({source: o, target: o});
         })
        .remove();

    // Stash the old positions for transition.
    nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
    });

    d3.select("svg")
        .call(d3.behavior.zoom()
        .scaleExtent([0.5, 5])
        .on("zoom", zoom));
};

d3.json("flare.json", function(json){
    root = json;
    root.x0 = height / 2;
    root.y0 = 0;
    root.children.forEach(collapse);
    update(root);
});

</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向 d3 可折叠树示例添加缩放功能? 的相关文章

  • 正则表达式中的“g”标志是什么意思?

    的含义是什么g正则表达式中的标志 之间有什么区别 g and g用于全局搜索 这意味着它将匹配所有出现的情况 通常你还会看到i这意味着忽略大小写 参考 全局 JavaScript MDN https developer mozilla or
  • 是否可以在没有 Javascript(仅 CSS)的情况下执行相同的操作(悬停效果)?

    我正在尝试创建一个带有图标的按钮像这样 http jsfiddle net pRdMc HTML div div class icon div span Send Email span div CSS button width 270px
  • Google reCaptcha 永远加载

    我在我的网站上使用 Google 的 reCaptcha 2 0 它曾经运行良好 但自从我向公众开放我的网站并获得了更多用户后 recaptcha 不再适用于大多数用户 它加载得很好 但一旦用户单击 我不是机器人 复选框 它会永远加载并且从
  • 使用 npm 作为构建工具连接文件

    我最近发现我可以使用 npm 作为任务运行程序 而不是 gulp 或 grunt 到目前为止 一切都很棒 lint stylus jade uglify watch 等 但串联部分 我似乎无法实现 gulp 是这样的 gulp task s
  • 使用 jQuery / .data() 避免内存泄漏

    我正在使用 jQuery 动态创建 HTML 元素 现在需要针对它们存储 JavaScript 数据 但是 我现在担心内存泄漏 因为我实际上从未在对象上调用 删除 我 append 和 detach 它们 但从不 remove jQuery
  • 无法填充名为“status”的数组

    我正在尝试做一些非常简单的事情 在 Javascript 中初始化一个数组 而且它在 Google Chrome 中不起作用 这是代码 status for i 0 i lt 8 i status i false alert status
  • 如果浏览器在 asp .net 中关闭,请从浏览器中注销?

    我的要求有点复杂 用户正在使用 Web 浏览器访问数据库 而在访问数据库时 如果用户关闭活动页面而不是注销会话 该会话需要自动注销 有人可以指导我如何做这个吗 我在母版页中使用了jquery onbeforeunload 我收到消息离开页面
  • Google Charts(AreaChart)如何检测缩放变化

    我正在画一个面积图 在覆盖层上有一些标记 我正在使用explorer选项 仅限水平 以便用户放大和缩小 问题是我找不到一种方法来通知缩放更改 以便有机会更新制造商位置 有一个图表范围变化事件 但它不是由 AreaChart 触发的 我尝试检
  • 如何为 HTML5 音频元素制作加载栏?

    我正在尝试为 HTML5 音频元素制作一个加载栏 显示加载 缓冲的百分比 对于视频标签 可以使用以下方法进行计算 video buffered end 0 video duration 但我无法让它与音频标签一起使用 它只是返回一个固定值
  • jQuery 验证日期范围问题

    我的代码中有很多地方有成对的相关开始和结束日期字段 范围 我需要验证开始日期早于结束日期 我正在使用 jQuery 验证插件 这是我的代码 http jsfiddle net jinglesthula dESz2 http jsfiddle
  • 光滑的旋转木马不工作

    我一直在尝试简单地实现 Slick Carousel 的工作 我已按照 Git 页面上的说明进行操作 https github com kenwheeler slick https github com kenwheeler slick 这
  • Typescript:如何在自定义过滤器中使用角度 $filter

    如何在自定义过滤器中使用 Angular filter 如何注入 filter依赖 module Filters export class CustomFilter public static Factory return function
  • 在 JavaScript 中定位提示弹出窗口

    我有一个如下所示的 JavaScript 提示 我想将提示放在屏幕中心 如何使用 javascript 做到这一点 function showUpdate var x var name prompt Please enter your na
  • 单击输入字段会触发窗口调整大小

    我有一个带有徽标 菜单和搜索的标题 当我在桌面上时 我会按该顺序显示所有元素 但如果我的窗口宽度小于 980 像素 菜单会隐藏 有一个切换按钮 并且徽标会与nav并附在徽标之后 如果宽度更大 则徽标将再次分离并附加到 DOM 中的旧位置 w
  • canvas.getContext('2D') 返回空值

    我创建了一个画布并将其命名为getContext 方法 但它返回null为上下文 这是我使用的代码 我在控制台中得到了这个
  • AngularJS 输入字段未从控制器内的 setTimeout 更新

    我正在使用 AngularJS 支持的页面 并且我需要在只读输入文本字段内显示正在运行的时钟 与data ng model 为了模拟运行的时钟 我使用了 JavaScript 调度程序setTimeout每 1000 毫秒调用一个函数 该函
  • 如何检查元素的内容是否为空,如果是,则在 jquery 中删除该元素

    我目前正在尝试选择某个 div 内没有内容的任何 h2 元素并将其删除 这是我的 html 代码 div class skipToContainer h2 class vidSkipTo Hello h2 h2 class vidSkipT
  • 如何在 JavaScript 中对关联数组进行排序?

    我需要为我的一个项目通过 JS 对关联数组进行排序 我发现这个函数在 Firefox 中运行得很好 但不幸的是它在 IE8 OPERA CHROME 中不起作用 无法找到使其在其他浏览器中运行的方法 或者找到另一个适合该目的的函数 我真的很
  • 跨浏览器:禁用输入字段的不同行为(文本可以/不能复制)

    我有一个被禁用的输入 html 字段 在某些浏览器 Chrome Edge Internet Explorer 和 Opera 中可以选择并复制文本 但至少在 Firefox 中这是不可能的 您可以通过在不同浏览器中执行以下代码来测试
  • 如何从配置加载套接字 io 事件监听器? [复制]

    这个问题在这里已经有答案了 我有使用套接字io 的nodejs 应用程序 我将存储在 config routes js 中的所有事件侦听器 module exports routes auth login controller auth a

随机推荐