2dimple.js/d3.js在窗口大小更改时自动调整图表大小

2dimple.js/d3.js auto size chart when window size changes

本文关键字:js 调整 d3 窗口大小 2dimple      更新时间:2023-09-26

我有下面的代码,它使用deplet.js绘制图表:http://jsbin.com/zacus/17/当调整浏览器窗口的大小(或调整jsbin窗格的大小)时,我希望图表也能调整大小以适应它的表单元格父单元格。从这个例子中可以看出,这种情况并没有发生。我曾尝试编写一个事件处理程序来更改图表的宽度或在图表变宽时重新绘制图表,但没有成功。

window.onresize= function redraw(){
  chart1.setBounds(70, 30, pTd.offsetWidth-150, 300);
  myLegend1.left = chart1.width + 100;
}

关于如何做到这一点,有什么建议吗?

编辑:经过一点实验,我找到了下面的代码,它似乎解决了我的问题。这是实现这一目标的最佳方式吗?

chart1.svg.attr("width", "100%")
  .attr("height", "100%")
  .attr("viewBox", "0 0 600 400");

我还没有在viewBox中尝试过,所以如果可以的话,这听起来是一个不错的解决方案。我使用setMargins作为图表的比例,并在调整大小时调用chart.draw。这有使用凹坑大小调整逻辑的好处——例如,当图表变得太小时,旋转x轴标签。

以下是网站上的一个例子:

// Set up a standard chart
var myChart;
d3.tsv("/data/example_data.tsv", function (data) {
    myChart = new dimple.chart(svg, data);
    // Fix the margins
    myChart.setMargins("60px", "30px", "110px", "70px");
    // Continue to set up a standard chart
    myChart.addCategoryAxis("x", "Month").addOrderRule("Date");
    myChart.addMeasureAxis("y", "Unit Sales");
    myChart.addSeries("Channel", dimple.plot.bar);
    // Set the legend using negative values to set the co-ordinate from the right
    myChart.addLegend("-100px", "30px", "100px", "-70px");
    myChart.draw();
});
// Add a method to draw the chart on resize of the window
window.onresize = function () {
    // As of 1.1.0 the second parameter here allows you to draw
    // without reprocessing data.  This saves a lot on performance
    // when you know the data won't have changed.
    myChart.draw(0, true);
};

在这里它正在运行