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

Time:08-27

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.

CodePudding user response:

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  />
  <path />
</svg>

CodePudding user response:

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>

  • Related