D3.js 如何使d3js直方图具有响应性

D3.js 如何使d3js直方图具有响应性,d3.js,responsive-design,D3.js,Responsive Design,我已经写了这个图表,它很好,非常简单,但没有反应,这是必须的。 我试过几件事,运气不好。我不是D3J方面的专家 我试过下面的方法,但没用 /*window resize operations*/ function resize() { console.log('----resize function----'); // update width width = parseInt(d3.select('#chartID').style('width'), 10); width =

我已经写了这个图表,它很好,非常简单,但没有反应,这是必须的。 我试过几件事,运气不好。我不是D3J方面的专家

我试过下面的方法,但没用

/*window resize operations*/
function resize() {
  console.log('----resize function----');
  // update width
  width = parseInt(d3.select('#chartID').style('width'), 10);
  width = width - margin.left - margin.right;

  height = parseInt(d3.select("#chartID").style("height"));
  height = height - margin.top - margin.bottom;
  console.log('----resiz width----'+width);
  console.log('----resiz height----'+height);
  // resize the chart
  xScale.rangeRoundBands([0, width], .1);
  yScale.range([height+100, 0]);

  yAxis.ticks(Math.max(height/50, 2));
  xAxis.ticks(Math.max(width/50, 2));

  d3.select(svgContainer.node().parentNode)
      .style('width', (width + margin.left + margin.right) + 'px');

  svgContainer.selectAll('.g')
      .attr("transform", function(d) { return "translate(" + xScale(d.name) + ",0)"; });

  svgContainer.selectAll("rect")
      .attr("x",function(d) { return d.name; })
      .attr("width", xScale.rangeBand());

  svgContainer.select('.x.axis').call(xAxis.orient('bottom')).selectAll("text").attr('dy','0.5em').attr('dx','-3em'); 
}

如果您只想缩放图表,SVG是可伸缩的(矢量图形)。 可以在SVG元素上设置和属性

如果同时设置这两个参数,并使用相对单位(如%)应用with,则SVG只需根据您的站点进行缩放,而无需通过js重新呈现图表

实际上,我只是将一个应用程序推到github,在那里我使用了这种方法


我用叉子叉起你的小提琴,添加了
viewbox
preserveSpectratio
和宽度
100%
。调整窗格大小时,图表将调整大小。请参见

请参见。您好,您的JSFIDLE很好,非常感谢您,我不是d3js方面的专家,但您的解决方案我将学习,因为d3是一个不错的选择。d3js现在必须提升他们所有的图表的响应能力,否则他们就完蛋了——再次感谢我的纠缠。安德格拉德说我能帮助你;)如果我的答案解决了你的问题,请将其标记为已接受答案。这样很明显,你的问题已经解决了,其他人可以看到哪个答案解决了你的问题