如何从Delaunay三角化SVG的矩形路径提取三角形坐标?
Hey there! Let's figure out how to extract those triangle coordinates from the SVG output you're seeing, even if the path elements look like rectangles at first glance. Here's what you can do step by step:
Check the SVG Path's
dAttribute
It's easy to mistake a triangle path for a rectangle if you're just skimming. Open your SVG in a text editor and look at thedattribute of a path element. A triangle path will follow this pattern:M x1 y1 L x2 y2 L x3 y3 Z(whereM= move to,L= line to,Z= close shape). If you see this, parse the x/y values directly to get your vertices. If theddefines a rectangle, the triangle data is probably stored elsewhere.Look for Custom Data Attributes
Many triangulation libraries store raw vertex data in customdata-*attributes on path elements. Check for attributes like:data-triangle-points(comma-separated x/y values, e.g.,"10,20 30,40 50,10")data-p0,data-p1,data-p2(each holding one vertex's coordinates)
These are often added specifically to preserve the original triangle data, even if the rendered path is a rectangle (used for styling or clipping purposes).
Check for Embedded JSON Data
Some libraries output all triangulation data in a<script>tag inside the SVG (formatted as JSON). Search for a block like this:<script type="application/json"> {"triangles": [[[10,20],[30,40],[50,10]], [[...], [...], [...]]]} </script>Parse this JSON to get a full list of all triangle vertices in one go.
Use Code to Extract Coordinates
Here are quick JavaScript snippets to pull the data:- Parsing the
dattribute:const trianglePath = document.querySelector('path'); const pathData = trianglePath.getAttribute('d'); const pointMatches = pathData.match(/([ML]\s+\d+\s+\d+)/g); const triangleVertices = pointMatches.map(match => { const [_, x, y] = match.match(/(\d+)\s+(\d+)/); return { x: parseFloat(x), y: parseFloat(y) }; }); console.log(triangleVertices); - Parsing custom data attributes:
const trianglePath = document.querySelector('path'); const p0 = trianglePath.getAttribute('data-p0').split(',').map(Number); const p1 = trianglePath.getAttribute('data-p1').split(',').map(Number); const p2 = trianglePath.getAttribute('data-p2').split(',').map(Number); const triangleVertices = [p0, p1, p2]; console.log(triangleVertices);
- Parsing the
Check the Library's Source Code
If all else fails, peek at the library's SVG generation code. You'll find exactly where it writes the triangle data—whether to the path'sdattribute, custom attributes, or an embedded script. This will give you a definitive answer on where to find the coordinates.
内容的提问来源于stack exchange,提问作者Hajar Ch

