【问题标题】:responsive D3 chart响应式 D3 图表
【发布时间】:2013-07-11 16:23:58
【问题描述】:

我有这个 D3 图表 - 几乎是开箱即用的。有没有办法让它响应并使用宽度和高度变量、innerRadius 和 outerRadius 的百分比?我在响应式网站上工作,需要根据屏幕大小/浏览器大小进行更改。

jsfiddle 在这里:http://jsfiddle.net/BTfmH/1/

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
html,
body {
  margin:0;
  padding:0;
  width:100%;
  height:100%;
}

.chart-container {
/*  width:50%;
  height:50%;*/
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
  var width = 350,
      height = 350,
      τ = 2 * Math.PI;

  var arc = d3.svg.arc()
      .innerRadius(100)
      .outerRadius(135)
      .startAngle(0);

var svg = d3.select("body").append("svg")
      .attr("width", width)
      .attr("height", height)
    .append("g")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")

  var background = svg.append("path")
      .datum({endAngle: τ})
      .style("fill", "green")
      .attr("d", arc);

  var foreground = svg.append("path")
    .datum({endAngle: .127 * τ})
      .style("fill", "grey")
      .attr("d", arc);

setInterval(function() {
  foreground.transition()
      .duration(750)
      .call(arcTween, Math.random() * τ);
}, 1500);

  function arcTween(transition, newAngle) {

    transition.attrTween("d", function(d) {

      var interpolate = d3.interpolate(d.endAngle, newAngle);

      return function(t) {

        d.endAngle = interpolate(t);

        return arc(d);
      };
    });
}
</script>

【问题讨论】:

标签: d3.js responsive-design


【解决方案1】:

您可以使用 SVG 元素上的 viewBox 和 preserveAspectRatio 属性的组合来调整图表大小。

完整示例请参见此 jsfiddle:http://jsfiddle.net/BTfmH/12/

var svg = d3.select('.chart-container').append("svg")
    .attr("width", '100%')
    .attr("height", '100%')
    .attr('viewBox','0 0 '+Math.min(width,height)+' '+Math.min(width,height))
    .attr('preserveAspectRatio','xMinYMin')
    .append("g")
    .attr("transform", "translate(" + Math.min(width,height) / 2 + "," + Math.min(width,height) / 2 + ")");

您甚至不需要使用此方法的 resize 处理程序。

【讨论】:

  • 非常感谢您提供的帮助!我特别感谢这一点,因为它没有得到答复/闲置了这么久!
  • @TechyDude,没问题——我自己也需要这个并且看到了你的问题。我在其他地方找不到好的答案,所以扩展了你的例子。
  • @SamSehnert,感谢您的回答,我在jsfiddle.net/adityap16/11edxrnq/1 做了类似的事情。但是当我将它移植到 React 中时,我的情节变得非常小,你能想到任何原因吗?
  • 我的超级巨星化身!
  • 感谢@SamSehnert
【解决方案2】:

您可以使用window.innerWidth 和window.innerHeight 来获取屏幕的尺寸并相应地设置您的图表,例如

var width = window.innerWidth,
    height = window.innerHeight,
    innerRadius = Math.min(width,height)/3,
    outerRadius = innerRadius + 30;

【讨论】:

  • 感谢您的回复拉斯!这在根据窗口页面调整图表大小方面确实有效。我如何让它随着浏览器窗口调整大小?
  • 您可以使用onresize 事件(参见例如this question),但您必须自己重绘。
猜你喜欢
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 2014-11-25
相关资源
最近更新 更多