简体   繁体   English

位置D3 SVG画布x / y和加载时的缩放级别

[英]Position D3 SVG Canvas x/y and Zoom Level On Load

I'm using D3 to create an organization chart. 我正在使用D3创建组织结构图。 I've got the data loading fine and have figured out how to make the canvas move by dragging the mouse as well a zoom with the mouse wheel. 我已经加载好数据,并且想出了如何通过拖动鼠标以及使用鼠标滚轮缩放来使画布移动。

My problem is that the org chart is rather large so when the document first loads the root node is out of the browser's view area and the zoom level is set fairly high. 我的问题是组织结构图相当大,因此当文档第一次加载时,根节点不在浏览器的视图区域内,并且缩放级别设置得很高。

I need to figure out how to set the viewable area of the canvas around the first node and set the initial zoom level to 100%. 我需要弄清楚如何在第一个节点周围设置画布的可视区域,并将初始缩放级别设置为100%。

I was able to create a solution thanks to @Lars Kotthoff. 感谢@Lars Kotthoff,我能够创建一个解决方案。

I retrieved the root node's x value from it's translate attribute (ie translate(x,y)) and then took the browser's width / 2 - the x value. 我从其translate属性(即translate(x,y))中检索了根节点的x值,然后获取了浏览器的宽度/ 2-x值。 I applied this value to the parent group's translate attribute which centers the document around the root node. 我将此值应用于父组的translate属性,该属性使文档围绕根节点居中。

var windowWidth = $(window).width();
var node0 = d3.select("#node-0");
var translate = parseTranslate(node0.attr("transform"));
var translateX = translate.x - (windowWidth / 2);
var svgGroup = d3.select("#svg_g");
svgGroup.attr("transform", "translate(-" + translateX + ",22) scale(1)"); // with 20 y padding

NOTE: Because I'm new to SVG and D3 I am still not sure how to get just the "x" value of a node's translate attribute so I created a function that parses the translate attribute with regex. 注意:因为我是SVG和D3的新手,所以我仍然不确定如何仅获取节点的translate属性的“ x”值,因此我创建了一个使用regex解析translate属性的函数。 I'm sure there is a better way of getting this value so if anyone wants to update my answer or add a comment for future readers that would increase the value of this question. 我确信有一种更好的方法来获取此值,因此,如果有人要更新我的答案或为将来的读者添加评论,这将增加此问题的价值。

The function I created is: 我创建的函数是:

function parseTranslate(str) {
var translate = {
    x: 0,
    y: 0,
    scale: 0
}

var pattern = /\((.+?)\)/g;
var matches = [];

while (match = pattern.exec(str)) {
    matches.push(match[1]);
}

if (matches.length) {
    if (matches.length == 1) {
        if (matches[0].indexOf(",") > -1) {
            var p = matches[0].split(',');
            translate.x = p[0];
            translate.y = p[1];
        } else {
            translate.scale = matches[0];
        }
    } else if (matches.length == 2) {
        var p = matches[0].split(',');
        translate.x = p[0];
        translate.y = p[1];
        translate.scale = matches[1];
    }
}
return translate;
}

I'm also using jQuery in my project to get the width of the browser (ex: $(window).width();) 我还在项目中使用jQuery来获取浏览器的宽度(例如:$(window).width();)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM