【发布时间】:2017-06-01 10:35:17
【问题描述】:
我刚刚开始掌握 D3 并希望在调整窗口大小时调整它的大小,我设法通过一些 javascript 来做到这一点,在下面的示例中被注释掉了,但是有一个 thread here 说该宽度和高度可以从 SVG 元素中去掉,它会在没有 javascript 的情况下响应地调整大小。遗憾的是,这对我不起作用,我正在使用最新的 IE11 和 Firefox 进行测试。
-
当我离开宽度和高度时,它只显示文本
**width="960" height="500"** 当我取消注释底部的 JS 时,它可以工作
- 当我包含宽度和高度时,大小不会随窗口大小而变化
sn-p 在下面但不起作用,因为我使用的是 D3 版本 4 和 JQ 版本 3.x,sn-p 工具似乎只允许早期版本。
如何在不取消注释 javascript 的情况下调整其大小?
我确信这很愚蠢而且很明显,但我已经坚持了很久!.. 谢谢
$(function () {
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = Math.min(width, height) / 2,
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var color = d3.scaleOrdinal(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var pie = d3.pie()
.sort(null)
.value(function (d) { return d.population; });
var path = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var label = d3.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
d3.csv("data.csv", function (d) {
d.population = +d.population;
return d;
}, function (error, data) {
if (error) throw error;
var arc = g.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
arc.append("path")
.attr("d", path)
.attr("fill", function (d) { return color(d.data.age); });
arc.append("text")
.attr("transform", function (d) { return "translate(" + label.centroid(d) + ")"; })
.attr("dy", "0.35em")
.text(function (d) { return d.data.age; });
});
// Uncomment this to make it resize with the window width changes
//var aspect = width / height,
// chart = d3.select('svg');
//d3.select(window)
// .on("resize", function () {
// var targetWidth = $(window).width();
// chart.attr("width", targetWidth);
// chart.attr("height", targetWidth / aspect);
// });
});
svg {
display: inline-block;
position: absolute;
top: 0;
left: 0;
}
body {
display: inline-block;
position: relative;
width: 100%;
vertical-align: middle;
background-color:#ffffe0;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<svg width="960" height="500" viewBox="0 0 900 600" preserveAspectRatio="xMidYMid meet"></svg>
数据.csv:
age,population
<5,2704659
5-13,4499890
14-17,2159981
18-24,3853788
25-44,14106543
45-64,8819342
=65,612463
【问题讨论】:
-
能否举一个你的data.csv的例子
-
是的,抱歉,是从网上的例子中截取的:
-
我将编辑问题以添加它
-
您的 sn-p 甚至无法执行!您的代码使用 D3 v4 而您引用的是 D3 v3.4.11。
-
我想我已经修复了 cdn 链接,但它仍然无法正常工作,因为 data.csv 不存在。
标签: javascript d3.js svg