问题
I am experimenting with this d3 demo and I am having trouble debugging why I am experiencing different behavior in Chrome vs. Safari/FireFox. If I run the full code below, it works in Chrome but not in Safari/Firefox. I seem to have isolated the problem to the following:
If I change this line:
var circles = chart.select("#points").selectAll("circle")
to this:
var circles = chart.selectAll("circle")
it works in Safari/Firefox/Chrome, but I want to understand what is happening and why the code below doesn't work. Any insight would be greatly appreciated.
Full Code
<svg>
<g id="chart">
<g id="bg">
</g>
<g id="countries">
</g>
<g id="points">
</g>
</g>
</svg>
<script type="text/javascript">
d3.json("costofliving.json", function(col) {
var cx = 200;
var cy = 132;
var cw = 400;
var ch = 400;
var svg = d3.select("svg");
var nticks = 14;
var price_min = 0;
var price_max = d3.max(col, function(d) {return d.price});
var rent_min = 0;
var rent_max = d3.max(col, function(d) {return d.rent});
var price_scale = d3.scale.linear()
.domain([price_min, price_max])
.range([ch, 0]);
var rent_scale = d3.scale.linear()
.domain([rent_min, rent_max])
.range([0, cw]);
var price_layout = d3.layout.histogram()
.value(function(d) { return d.price })
.range([0, price_max])
.bins(nticks);
var rent_layout = d3.layout.histogram()
.value(function(d) { return d.rent })
.range([0, rent_max])
.bins(nticks);
var chart = svg.append("g")
.attr("transform", "translate(" + [cx, cy] + ")");
chart.append("g")
.attr("id", "countries")
.style("opacity", 0);
chart.append("g")
.attr("id", "points")
var circles = chart.select("#points").selectAll("circle")
.data(col);
circles.enter()
.append("circle")
circles.attr({
r: 6,
cx: function(d,i) {
return rent_scale(d.rent);
},
cy: function(d,i) {
return price_scale(d.price);
}
})
});
</script>
回答1:
You need to set a width and height for any svg element in Firefox. According to the W3C Spec, the svg element will use "100%" as default, but my Firefox 17 (and probably other browsers) may not yet implement it like that.
When setting some absolute values in your code it works as expected.
<svg width="600" height="600">
来源:https://stackoverflow.com/questions/13527125/d3-js-need-help-debugging-differences-in-chrome-safari-and-firefox