d3 / d3-polygon

Geometric operations for two-dimensional polygons.
https://d3js.org/d3-polygon
ISC License
97 stars 25 forks source link

More easily import polygon points #13

Closed kipscripts closed 4 years ago

kipscripts commented 6 years ago

Since the polygon points are a simple string of "x1,y1 x2,y2, ... xn,yn" in the SVG XML, I found it much simpler to modify your polygonArea function to utilize the string values rather than try to convert to your expected nested arrays. Very minor tweaks adding a few splits, but it seems much more friendly for working with polygons on the fly. Feel free to incorporate them if you find them useful.

            var svgDoc = document.getElementById("svg");
            var string = d3.event.target.id;
            var poly = d3.select(svgDoc).select("polygon#" + string);
            var points = poly.attr("points");
            var polygon = points.split(" ");            
            var i = 0,
                n = polygon.length - 1,
                a,
                b = polygon[n].split(","),
                area = 0;
            while (i++ < n)    {
                a = b;
                b = polygon[i].split(",");
                area += a[1] * b[0] - a[0] * b[1];
            }
            area /= 2;
mbostock commented 4 years ago

Defining a serialized representation for polygons is out-of-scope for this library.