我有一个报告页面,其中包含三个 D3 JS v3 图和一些表格数据。窗口最大化时,页面看起来很棒,但是当用户调整浏览器窗口大小时,它开始表现得很奇怪,即每个图都会溢出包含的 div
等。
经过一番研究,我发现我只需要为每个图设置根 svg 的 viewBox
属性即可,即
var margin = {top: 40, right: 20, bottom: 20, left: 20},
width = 450 - margin.left - margin.right,
height = 370 - margin.top - margin.bottom;
var chartSvg = d3.select("#myPlotDivId")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("viewBox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom))
.attr("preserveAspectRatio", "xMidYMid meet")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
我可以在特定的 AngularJS Controller 中执行此操作,并且没有问题。但是,每次调整窗口大小时,我还需要更新所有三个绘图 svg。有一个nice JSFiddle demonstrating this :
var aspect = chartSvg.width() / chartSvg.height(),
container = chartSvg.parent();
$(window).on("resize", function() {
var targetWidth = container.width();
chartSvg.attr("width", targetWidth);
chartSvg.attr("height", Math.round(targetWidth / aspect));
}).trigger("resize");
但是,我更愿意在 Controller 和创建绘图的函数中执行此操作...我该如何执行此操作?我不希望在页面中调用 Window 事件来调用我的 Controller 或为此创建一个全局指令。有什么想法吗?
最佳答案
首先,我希望你有一些包装 d3 代码的 Angular 组件/指令,如果没有 - 这是你应该做的事情。 那么这个组件应该接受宽度和高度:
app.component('myd3Plot', ...
width: '<',
height: '<'
在父 Controller /组件中,您有用于调整窗口大小和调整子图大小的监听器:
window.on('resize', function() {
vm.child1.height = ...
vm.child2.height = ...
})
<myd3-plot height="$ctrl.child1.height"...
<myd3-plot height="$ctrl.child2.height"...
关于javascript - D3 和 Angular : What's the best way to resize multiple plots on window resize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43782096/