Add tests for d3.geom.polygon and fix centroid bug.

d3.geom.polygon(…).area() assumes screen pixel coordinates with (0, 0)
at the top left, and y increasing going downwards.  This results in a
positive area for counterclockwise coordinates.  Howver, the default
centroid calculation was assuming "usual" Cartesian coordinates with y
increasing going upwards, hence the centroid coordinates were
incorrectly multiplied by -1.

This fix won't affect d3.geo.path(…).centroid() as it passes a constant
to d3.geom.centroid.
This commit is contained in:
Jason Davies 2011-10-08 17:30:17 +01:00
Родитель 0e0ba08900
Коммит 3740741441
4 изменённых файлов: 37 добавлений и 3 удалений

Просмотреть файл

@ -198,7 +198,7 @@ d3.geom.polygon = function(coordinates) {
a,
b,
c;
if (!arguments.length) k = 1 / (6 * coordinates.area());
if (!arguments.length) k = -1 / (6 * coordinates.area());
while (++i < n) {
a = coordinates[i];
b = coordinates[i + 1];

2
d3.geom.min.js поставляемый

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Просмотреть файл

@ -21,7 +21,7 @@ d3.geom.polygon = function(coordinates) {
a,
b,
c;
if (!arguments.length) k = 1 / (6 * coordinates.area());
if (!arguments.length) k = -1 / (6 * coordinates.area());
while (++i < n) {
a = coordinates[i];
b = coordinates[i + 1];

34
test/geom/polygon-test.js Normal file
Просмотреть файл

@ -0,0 +1,34 @@
require("../env");
require("../../d3");
require("../../d3.geom");
var vows = require("vows"),
assert = require("assert");
var suite = vows.describe("d3.geom.polygon");
suite.addBatch({
"polygon": {
topic: function() {
return d3.geom.polygon;
},
"area": {
"last point equal to start point": function(polygon) {
assert.equal(polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]).area(), 1);
},
"implicitly ending at start point": function(polygon) {
assert.equal(polygon([[0, 0], [0, 1], [1, 1], [1, 0]]).area(), 1);
}
},
"centroid": {
"last point equal to start point": function(polygon) {
assert.deepEqual(polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]).centroid(), [.5, .5]);
},
"implicitly ending at start point": function(polygon) {
assert.deepEqual(polygon([[0, 0], [0, 1], [1, 1], [1, 0]]).centroid(), [.5, .5]);
}
}
}
});
suite.export(module);