增加d3 SVG容器大小

时间:2016-04-15 14:35:53

标签: javascript d3.js svg sankey-diagram

我正在尝试动态增加SVG容器的大小,以便它适合所有数据。有一个小提琴解释了SVG的动态增长:http://jsfiddle.net/CKW5q/

然而,相同的概念对于双向sankey图表(d3)并不起作用。以下是调用以扩展父节点的函数:

function expand(node) {
  node.state = "expanded";
  node.children.forEach(function (child) {
  child.state = "collapsed";
  child._parent = this;
  child.parent = null;
  containChildren(child);
          }, node);
  HEIGHT = HEIGHT + node.children.length * 10; //update height by 10px per child
  WIDTH = WIDTH + node.children.length * 10;//update width
 }
  svg.attr("height", HEIGHT); // update svg height

这给出了非常奇怪的结果。它肯定会增加容器,但遗憾的是保持原始SVG尺寸不变:

Result 我想在脚本开头声明的SVG HEIGHT和WIDTH需要更新,由于某些原因我无法更新。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

You will need to do something like this:

var Chart = (function(window, d3) {

    (init code that doesn't change on resize here)

    render();

    function render() {
        updateDimensions();
        (code that needs to be re-rendered on resize here)
    }

    function updateDimensions() {
        margin = {top: 100, right: 40, bottom: 80, left: 80}; // example

        width = window.innerWidth - margin.left - margin.right;
        height = window.innerHeight - margin.top - margin.bottom;
    }

    return {
        render: render
    }
})(window, d3);

window.addEventListener('resize', Chart.render);