Tec*_*ude 56 responsive-design d3.js
我有这个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>
Run Code Online (Sandbox Code Playgroud)
Sam*_*ert 129
您可以使用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 + ")");
Run Code Online (Sandbox Code Playgroud)
您甚至不需要resize使用此方法的处理程序.
您可以使用window.innerWidth和window.innerHeight获取屏幕的尺寸并相应地设置图表,例如
var width = window.innerWidth,
height = window.innerHeight,
innerRadius = Math.min(width,height)/3,
outerRadius = innerRadius + 30;
Run Code Online (Sandbox Code Playgroud)