微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – d3.js强制布局自动缩放/缩放加载后

我正在使用来自Flowingdata.com的 this nice force layout创建一个网络图.

我的图表目前显示了5到750个节点之间的关系.它适用于一些自定义更改以适应我的需要.但是有一件事我不能上班.我有一个viewBox与preserveAspectRatio自动适应它所在的容器.但是,根据节点的数量,边缘总是有一些节点(主要是top和buttom)被切断.如果节点很少,它会在中间显示它们,它周围有巨大的空白空间(它是一个大的容器).

有没有办法自动缩放或缩放布局自动适应?所以一个大的布局有点缩小,一个小的布局放大.我有一个缩放事件设置,所以滚动和平移工作就像一个魅力.但是它能自动地做到这一点来适应内容吗?

d3.js启动代码

vis = d3.select(selection)
        .append("svg")
        .attr("viewBox","0 0 " + width + " " + height )
        .attr("preserveAspectRatio","xMidYMid meet")
        .attr("pointer-events","all")
        .call(d3.behavior.zoom().scaleExtent([.1,3])
                        .on("zoom",redraw)).append('g');

解决方法

迄今为止所有其他答案都需要访问数据,并通过它进行迭代,所以复杂度至少为O(节点).我一直在寻找并找到一种完全基于已经呈现的视觉大小的方法,getBBox()可以希望是O(1).它的尺寸和父容器的大小无关紧要,它的布局如何.我基于 http://bl.ocks.org/mbostock/9656675设法鞭打这个:
var root = // any svg.select(...) that has a single node like a container group by #id

function lapsedZoomFit(ticks,transitionDuration) {
    for (var i = ticks || 100; i > 0; --i) force.tick();
    force.stop();
    zoomFit(transitionDuration);
}

function zoomFit(transitionDuration) {
    var bounds = root.node().getBBox();
    var parent = root.node().parentElement;
    var fullWidth = parent.clientWidth || parent.parentNode.clientWidth,fullHeight = parent.clientHeight || parent.parentNode.clientHeight;
    var width = bounds.width,height = bounds.height;
    var midX = bounds.x + width / 2,midY = bounds.y + height / 2;
    if (width == 0 || height == 0) return; // nothing to fit
    var scale = 0.85 / Math.max(width / fullWidth,height / fullHeight);
    var translate = [fullWidth / 2 - scale * midX,fullHeight / 2 - scale * midY];

    console.trace("zoomFit",translate,scale);

    root
        .transition()
        .duration(transitionDuration || 0) // milliseconds
        .call(zoom.translate(translate).scale(scale).event);
}

原文地址:https://www.jb51.cc/js/154237.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐