简体   繁体   English

通过JS中的一组元素在SVG中创建多边形

[英]Create a polygon in SVG from a group of elements in JS

I have an SVG with groups of elements (which are all a uniform shape but the group shape can vary. Obviously putting an outline on the group will give me a rectangle shape. What I am trying to achieve is a polygon that outlines the group giving a rough trace of the items: 我有一个带有元素组的SVG(元素都是统一的形状,但是组的形状可以变化。显然在组上放一个轮廓会给我一个矩形形状。我想要实现的是一个多边形,它概述了组粗略的项目跟踪:

http://codepen.io/wroughtec/pen/OXvRrq http://codepen.io/wroughtec/pen/OXvRrq

(below is an example with circles although have also included a path example as that is what I am actually being given) (下面是一个带有圆圈的示例,尽管其中也包括一个路径示例,因为这实际上是我得到的)

<h2>No Outline</h2>
<svg viewbox="0 0 1000 200">
  <g>
    <circle cx="20" cy="20" r="10" fill="grey" />
    <circle cx="50" cy="20" r="10" fill="grey" />
    <circle cx="50" cy="50" r="10" fill="grey" />
    <circle cx="80" cy="50" r="10" fill="grey" />
    <circle cx="110" cy="50" r="10" fill="grey" />
    <circle cx="140" cy="50" r="10" fill="grey" />
    <circle cx="50" cy="80" r="10" fill="grey" />
    <circle cx="80" cy="80" r="10" fill="grey" />
    <circle cx="110" cy="80" r="10" fill="grey" />
    <circle cx="140" cy="80" r="10" fill="grey" />
    <circle cx="170" cy="80" r="10" fill="grey" />
    <circle cx="200" cy="80" r="10" fill="grey" />
    <circle cx="170" cy="110" r="10" fill="grey" />
    <circle cx="200" cy="110" r="10" fill="grey" />
  </g>
</svg>

I need to be able to do this automatically in JS but getting the x and y of the circles gives me the center point so my manual one I have had to cheat to expand to the outer shape of the circles and remove unnecessary points (ie points on the same line or in the middle). 我需要能够在JS中自动执行此操作,但是获取圆的x和y给了我中心点,因此我不得不作弊以扩展到圆的外部形状并删除不必要的点(即点)在同一行或中间)。

It sounds like what you're looking for is the convex hull of the points. 听起来您正在寻找的是这些点的凸包

D3.js implements this, and a good example can be found here . D3.js实现了这一点,可以在这里找到一个很好的例子。 (The code is rather lengthy, so I won't reproduce it here; the main function of interest is d3.geom.hull ) (代码相当冗长,因此在这里我不会重现;感兴趣的主要功能是d3.geom.hull

Note that D3.js v4 was just recently released, and almost all code online (including what I linked) is written for v3. 请注意,D3.js v4是最近发布的,几乎所有在线代码(包括我链接的代码)都是为v3编写的。 There are significant changes between the two, but v4 still has a convex hull function . 两者之间有很大的变化,但是v4仍然具有凸包功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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