我正在用d3.js绘制散点图。在这个问题的帮助下:
Get the size of the screen, current web page and browser window
我用的是这个答案:
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
因此,我可以像这样将我的图与用户的窗口相匹配:
var svg = d3.select("body").append("svg")
.attr("width", x)
.attr("height", y)
.append("g");
现在,我希望当用户调整窗口大小时,会有一些东西负责调整绘图的大小。
附言:我没有在我的代码中使用jQuery。
发布于 2013-04-29 01:30:08
function updateWindow(){
x = w.innerWidth || e.clientWidth || g.clientWidth;
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
svg.attr("width", x).attr("height", y);
}
d3.select(window).on('resize.updatesvg', updateWindow);
发布于 2014-05-03 10:40:25
如果调整大小的代码几乎和构建图形的代码一样长,那就有点丑陋了。因此,与其调整现有图表的每个元素的大小,为什么不简单地重新加载它呢?下面是我的工作原理:
function data_display(data){
e = document.getElementById('data-div');
var w = e.clientWidth;
// remove old svg if any -- otherwise resizing adds a second one
d3.select('svg').remove();
// create canvas
var svg = d3.select('#data-div').append('svg')
.attr('height', 100)
.attr('width', w);
// now add lots of beautiful elements to your graph
// ...
}
data_display(my_data); // call on page load
window.addEventListener('resize', function(event){
data_display(my_data); // just call it again...
}
关键的一行是d3.select('svg').remove();
。否则,每次调整大小都会在前一个元素下面添加另一个SVG元素。
发布于 2014-05-13 05:31:41
在强制布局中,简单地设置“height”和“width”属性将无法将绘图重新居中/移动到svg容器中。然而,有一个非常简单的答案,适用于here的强制布局。总而言之:
使用你喜欢的相同(任意)事件。
window.on('resize', resize);
然后假设你有svg和force变量:
var svg = /* D3 Code */;
var force = /* D3 Code */;
function resize(e){
// get width/height with container selector (body also works)
// or use other method of calculating desired values
var width = $('#myselector').width();
var height = $('#myselector').height();
// set attrs and 'resume' force
svg.attr('width', width);
svg.attr('height', height);
force.size([width, height]).resume();
}
通过这种方式,您不需要重新渲染整个图形,我们设置属性,然后d3根据需要重新计算。至少当你使用一个重力点时,这是可行的。我不确定这是否是这个解决方案的先决条件。任何人能证实或否认吗?
干杯,g
https://stackoverflow.com/questions/16265123
复制相似问题