问题
I'm using D3 to draw some pieces of information on canvas. And I got my aim in version 3 but failed in version 4 (Of course, I had changed the updated functions in version 4 such as d3.geo.mercator()
to d3.geoMercator()
). I debugged some relative functions and found the projection function was different.
In Version 3:
function projection(point) {
point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
return [ point[0] * k + δx, δy - point[1] * k ];
}
In Version 4:
function projection(point) {
point = projectRotate(point[0] * radians, point[1] * radians);
return [point[0] * k + dx, dy - point[1] * k];
}
My code Snippets is following:
var d3Projection = d3.geoMercator().scale(1).translate([0, 0]);
// var d3Projection = d3.geo.mercator().scale(1).translate([0, 0]);
var d3Path = d3.geoPath().projection(d3Projection);
// var d3Path = d3.geo.path().projection(d3Projection);
var pixelBounds = d3Path.bounds(features);
var pixelBoundsWidth = pixelBounds[1][0] - pixelBounds[0][0];
var pixelBoundsHeight = pixelBounds[1][1] - pixelBounds[0][1];
I debugged there and found the value of 'δx' was different from 'dx', which is the same condition on 'δy(dy)'
Debugging in Version 4 Debugging in Version 3
Could you someone explain the differences in this condition, please?
And what's the meaning of dx(δx), dy(δy) ?
D3 V3 correct demo.
D3 V4 The center coordinate is wrong. wrong demo.
_______________________________________________________________________________ I found the different code which result into my wrong demo This code was changed from v3.5.17, if I change this line code back to v3.5.16, everything will be OK. I will get the reason.
回答1:
The projection function in vanilla D3v3 and v4 is identical, your problem is that you're using some modified D3v3 version. If you try running this snippet in your D3v3 environment (assiming the topojson is loaded in var topo
):
var features = topojson.feature(topo, topo.objects.counties);
var d3Projection = d3.geo.mercator().scale(1).translate([0, 0]);
var d3Path = d3.geo.path().projection(d3Projection);
console.log(JSON.stringify(d3Path.bounds(features)));
you'll get
[[-3.141592653589793,-3.141592653589793],[3.141592653589793,3.141592653589793]]
If however you load current https://d3js.org/d3.v3.min.js
, the same exact snippet will produce
[[2.110384445824674,-0.5558860193147427],[2.1337212032517625,-0.5298056661805025]]
which is the same as V4. So you either need to fix your code to work with current D3 (v3 and v4), or modify your D3v4 in the same way as D3v3.
来源:https://stackoverflow.com/questions/49397496/the-change-of-polygon-contain-make-my-demo-wrong-in-d3