无法使用d3.js剪裁多边形

时间:2015-03-19 16:54:26

标签: javascript d3.js geometry polygons

我正在尝试拍摄多边形并使用其相交区域剪切另一个多边形。我认为d3.geom.polygon的方法剪辑可以工作,但是当我在下面的小提琴中尝试它时,我似乎得到了各种奇怪的问题。

http://jsfiddle.net/RussellAsher/335089x2/8/

如果有人知道如果有或没有d3.js我会这样做,我会永远感激。

我试图使用的d3方法:

var p1 = d3.geom.polygon(arrayOfPolygons[0].points);
var p2 = d3.geom.polygon(arrayOfPolygons[1].points);
p2.clip(p1);

1 个答案:

答案 0 :(得分:2)

d3.js来源:

https://github.com/mbostock/d3/blob/master/src/geom/polygon.js#L49-L86

在第49行,您可以阅读:

// The Sutherland-Hodgman clipping algorithm.
// Note: requires the clip polygon to be counterclockwise and convex.
d3_geom_polygonPrototype.clip = function(subject) {
...
}

你应该像这样使多边形反向:

enter image description here

在你的情况下:

var vis = d3.select("body").append("svg").attr({
    width: 1000,
    height: 667
}),

// I deleted scales there to make the code smaller

arrayOfPolygons = [{
    name: "polygon 1",
    points: []
}, {
    name: "polygon 2 ",
    points: []
}];

// clockwise polygon
arrayOfPolygons[0].points = [
    [5.5, 15.5],
    [24.0, 15.5],
    [20.5, 20],
    [12.0, 45.5],
    [4.0, 20]
];
// counterclockwise polygon
arrayOfPolygons[1].points = [
    [4.5, 24.5],
    [14.0, 24.5],
    [18.5, 20],
    [0.0, 20]
];

var p1 = d3.geom.polygon(arrayOfPolygons[0].points);
var p2 = d3.geom.polygon(arrayOfPolygons[1].points);
var p_x = p1.slice();// cloned polygon
p2.clip(p_x);// cloned polygon clipped

// the first polygon
vis.append("svg:polygon").attr({
    points: p1,
    stroke: "black",
    fill: "none"
});

// the second polygon
vis.append("svg:polygon").attr({
    points: p2,
    stroke: "black",
    fill: "none"
});

// clipped part
vis.append("svg:polygon").attr({
    points: p_x,
    stroke: "red",
    fill: "yellow"
});

最后结果:

DEMO:http://jsfiddle.net/335089x2/12/

现在您可以添加data()功能并进行缩放。