简体   繁体   中英

Convert array of polygon [x,y] coordinates to SVG <path>

Say I have the following polygon:

var polygon = [[52, 57], [27, 58], [34, 21], [52, 57]]

How could I convert this to an SVG path element in JavaScript (NPM modules are fine also), or more specifically, the d part of the SVG path element, example (this doesn't match up with my polygon, just an example <path>):

<path d="M 95.167 154.584 L 319.986 128.067 L 178.771 305.139 L 95.167 154.584 Z"></path>

I tried looking it up, but all I could find was the exact opposite of what I was trying to do: converting svg to x,y coordinates. I don't know much about how SVG works internally, so I don't even know how to approach this myself.

There are two ways to do this. You can use a Path. Path d attributes have a syntax but if all you want to do is draw a polygon then you only need to know M, L and Z (as the comments have described).

I would suggest, if you want to draw a polygon, to use <polygon> . The polygon points attribute only requires a string containing all the numbers (a flattened version of your array) delimited by commas or spaces.

 let polyCoords = [[52, 57], [27, 58], [34, 21], [52, 57]]; document.querySelector("path").setAttribute("d", polyCoords.map((c,i) => i?`${c[0]} ${c[1]}`:`M${c[0]} ${c[1]} L`).join(" ") + "Z" ); document.querySelector("polygon").setAttribute("points", polyCoords.map((c) => c.join(" ")).join(" "));
 .line { stroke-width: 4; stroke: black; fill: #0000; }.red-line { stroke-width: 6; stroke: red; fill: #0000; }
 <svg> <polygon class="red-line" /> <path class="line"/> </svg>

Like CCProg says in the comments, you can just join the polycoordinates for a path , because the L/l (line) setting is not required:

 <coords-svg fill="gold" coords="[[52, 57],[27, 58],[34, 21],[52, 57]]"></coords-svg> <coords-svg fill="green" coords="[[2, 15],[57, 58],[5, 57]]"></coords-svg> <script> customElements.define("coords-svg", class extends HTMLElement{ connectedCallback(){ let arr = JSON.parse(this.getAttribute("coords")); let dPath = arr.flat().join(" "); let fill = this.getAttribute("fill"); this.style.display = "inline-block"; this.style.width = "200px"; this.innerHTML = `<svg viewBox="0 0 100 100"><path d="M${dPath}Z" fill="${fill}" /></svg>`; } }); </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM