响应D3图表 [英] responsive D3 chart

查看:123
本文介绍了响应D3图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this D3 chart - pretty much out of the box. Is there a way to make it responsive and use percentages for the width and height variables, innerRadius, and outerRadius? I'm workign on a responsive site and need this to change based on screen size/browser size.

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

jsfiddle here: 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>


推荐答案

您可以使用 viewBox preserveAspectRatio 属性。

此jsfiddle的完整示例: http://jsfiddle.net/BTfmH/12/

See this jsfiddle for the full example: 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 此方法的处理程序。

You won't even need a resize handler with this method.

这篇关于响应D3图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆