从javascript中的点数组绘制SVG多边形

Joe*_*Joe 1 javascript arrays html5 svg

如果有这样的数组,(arr包括点)

arr = [ [ 0,0 ], 
             [ 50,50 ],
             [ 25,25 ], ];
Run Code Online (Sandbox Code Playgroud)

我想使用此数组绘制SVG多边形。

起初,我认为这段代码可以,但是事实并非如此。

<polygon points="arr[0][0],arr[0][1] arr[1][0],arr[1][1] arr[2][0],arr[2][1]" style = "fill:lime; stroke:purple; stroke-width:3;/">
Run Code Online (Sandbox Code Playgroud)

请让我知道如何使用点数组制作多边形。请编写一些示例代码。

Rob*_*son 5

您可以使用SVG DOM进行此操作,尽管除非您设置笔触,否则不会显示点形成直线的多边形。

var svg = document.getElementById("svg");
var polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
svg.appendChild(polygon);

var array = arr = [ [ 0,0 ], 
             [ 50,50 ],
             [ 25,25 ], ];

for (value of array) {
  var point = svg.createSVGPoint();
  point.x = value[0];
  point.y = value[1];
  polygon.points.appendItem(point);
}
Run Code Online (Sandbox Code Playgroud)
polygon {
  stroke: black;
}
Run Code Online (Sandbox Code Playgroud)
<svg id="svg">
</svg>
Run Code Online (Sandbox Code Playgroud)

  • 这是一个完整的代码示例。单击运行片段以运行它。 (2认同)