Skip to content

Commit 3740741

Browse files
committed
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.
1 parent 0e0ba08 commit 3740741

4 files changed

Lines changed: 37 additions & 3 deletions

File tree

d3.geom.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ d3.geom.polygon = function(coordinates) {
198198
a,
199199
b,
200200
c;
201-
if (!arguments.length) k = 1 / (6 * coordinates.area());
201+
if (!arguments.length) k = -1 / (6 * coordinates.area());
202202
while (++i < n) {
203203
a = coordinates[i];
204204
b = coordinates[i + 1];

d3.geom.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/geom/polygon.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ d3.geom.polygon = function(coordinates) {
2121
a,
2222
b,
2323
c;
24-
if (!arguments.length) k = 1 / (6 * coordinates.area());
24+
if (!arguments.length) k = -1 / (6 * coordinates.area());
2525
while (++i < n) {
2626
a = coordinates[i];
2727
b = coordinates[i + 1];

test/geom/polygon-test.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
require("../env");
2+
require("../../d3");
3+
require("../../d3.geom");
4+
5+
var vows = require("vows"),
6+
assert = require("assert");
7+
8+
var suite = vows.describe("d3.geom.polygon");
9+
10+
suite.addBatch({
11+
"polygon": {
12+
topic: function() {
13+
return d3.geom.polygon;
14+
},
15+
"area": {
16+
"last point equal to start point": function(polygon) {
17+
assert.equal(polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]).area(), 1);
18+
},
19+
"implicitly ending at start point": function(polygon) {
20+
assert.equal(polygon([[0, 0], [0, 1], [1, 1], [1, 0]]).area(), 1);
21+
}
22+
},
23+
"centroid": {
24+
"last point equal to start point": function(polygon) {
25+
assert.deepEqual(polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]).centroid(), [.5, .5]);
26+
},
27+
"implicitly ending at start point": function(polygon) {
28+
assert.deepEqual(polygon([[0, 0], [0, 1], [1, 1], [1, 0]]).centroid(), [.5, .5]);
29+
}
30+
}
31+
}
32+
});
33+
34+
suite.export(module);

0 commit comments

Comments
 (0)