Skip to content

Commit dbbe66d

Browse files
committed
Add diamond shape
1 parent ef4ec0d commit dbbe66d

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

demo/shapes.html

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414

1515
.node rect,
1616
.node circle,
17-
.node ellipse {
17+
.node ellipse,
18+
.node polygon {
1819
stroke: #333;
1920
fill: #fff;
2021
stroke-width: 1.5px;
@@ -42,6 +43,7 @@ <h1>Dagre D3 Demo: Shapes</h1>
4243
g.setNode("rect", { shape: "rect" });
4344
g.setNode("circle", { shape: "circle" });
4445
g.setNode("ellipse", { shape: "ellipse" });
46+
g.setNode("diamond", { shape: "diamond" });
4547

4648
var svg = d3.select("svg"),
4749
inner = svg.select("g");

lib/shapes.js

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33
var intersectRect = require("./intersect/intersect-rect"),
44
intersectEllipse = require("./intersect/intersect-ellipse"),
5-
intersectCircle = require("./intersect/intersect-circle");
5+
intersectCircle = require("./intersect/intersect-circle"),
6+
intersectPolygon = require("./intersect/intersect-polygon");
67

78
module.exports = {
89
rect: rect,
910
ellipse: ellipse,
10-
circle: circle
11+
circle: circle,
12+
diamond: diamond
1113
};
1214

1315
function rect(parent, bbox, node) {
@@ -55,3 +57,25 @@ function circle(parent, bbox, node) {
5557

5658
return shapeSvg;
5759
}
60+
61+
// Circumscribe an ellipse for the bounding box with a diamond shape. I derived
62+
// the function to calculate the diamond shape from:
63+
// http://mathforum.org/kb/message.jspa?messageID=3750236
64+
function diamond(parent, bbox, node) {
65+
var w = (bbox.width * Math.SQRT2) / 2,
66+
h = (bbox.height * Math.SQRT2) / 2,
67+
points = [
68+
{ x: 0, y: -h },
69+
{ x: -w, y: 0 },
70+
{ x: 0, y: h },
71+
{ x: w, y: 0 }
72+
],
73+
shapeSvg = parent.insert("polygon", ":first-child")
74+
.attr("points", points.map(function(p) { return p.x + "," + p.y; }).join(" "));
75+
76+
node.intersect = function(p) {
77+
return intersectPolygon(node, points, p);
78+
};
79+
80+
return shapeSvg;
81+
}

0 commit comments

Comments
 (0)