增加 d3 SVG 容器大小
Increasing d3 SVG container size
我正在尝试动态增加我的 SVG 容器的大小,以便它适合所有数据。有一个fiddle解释了SVG的动态增加:http://jsfiddle.net/CKW5q/
但是,相同的概念不适用于双向散基图 (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 尺寸不变:
我想在脚本开头声明的 SVG HEIGHT 和 WIDTH 需要更新,但由于某些原因无法更新。任何帮助将不胜感激。
您需要执行以下操作:
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);
我正在尝试动态增加我的 SVG 容器的大小,以便它适合所有数据。有一个fiddle解释了SVG的动态增加:http://jsfiddle.net/CKW5q/
但是,相同的概念不适用于双向散基图 (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 尺寸不变:
您需要执行以下操作:
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);