六角形组周围的轮廓

时间:2016-07-20 08:56:08

标签: javascript html5 grid hexagonal-tiles

我的六边形网格中有一组六边形,我喜欢用边框勾勒出轮廓。

到目前为止它是这样的:

enter image description here

所需的输出:

enter image description here

我已经存储了该组中每个六边形的所有cotrner点。我想这些点可以用来计算稍后组周围的边界。

[[{"x":123.39745962155612,"y":260},{"x":101.74682452694516,"y":272.5},{"x":80.0961894323342,"y":260},{"x":80.0961894323342,"y":235},{"x":101.74682452694516,"y":222.5},{"x":123.39745962155612,"y":235}],[{"x":145.0480947161671,"y":222.5},{"x":123.39745962155614,"y":235},{"x":101.74682452694518,"y":222.5},{"x":101.74682452694518,"y":197.5},{"x":123.39745962155614,"y":185},{"x":145.0480947161671,"y":197.5}],[{"x":166.69872981077808,"y":260},{"x":145.0480947161671,"y":272.5},{"x":123.39745962155612,"y":260},{"x":123.39745962155612,"y":235},{"x":145.0480947161671,"y":222.5},{"x":166.69872981077805,"y":235}],[{"x":188.34936490538905,"y":297.5},{"x":166.69872981077808,"y":310},{"x":145.0480947161671,"y":297.5},{"x":145.0480947161671,"y":272.5},{"x":166.69872981077808,"y":260},{"x":188.34936490538902,"y":272.5}],[{"x":188.34936490538905,"y":222.5},{"x":166.69872981077808,"y":235},{"x":145.0480947161671,"y":222.5},{"x":145.0480947161671,"y":197.5},{"x":166.69872981077808,"y":185},{"x":188.34936490538902,"y":197.5}],[{"x":210,"y":260},{"x":188.34936490538902,"y":272.5},{"x":166.69872981077805,"y":260},{"x":166.69872981077805,"y":235},{"x":188.34936490538902,"y":222.5},{"x":209.99999999999997,"y":235}],[{"x":231.65063509461098,"y":297.5},{"x":210,"y":310},{"x":188.34936490538902,"y":297.5},{"x":188.34936490538902,"y":272.5},{"x":210,"y":260},{"x":231.65063509461095,"y":272.5}]]

还添加了一个实时example,以了解网格到目前为止的工作情况。

现在我想弄清楚我究竟是如何确定如何生成边框的。

现在我该如何准确生成边框? 我应该找到这个组的中心,然后 找到距离更远的所有点,并且 然后连接它们?

正如下面讨论的人所建议的,我尝试按照[X,Y]坐标对点进行排序,并删除了所有重复的坐标,但它变成了这场灾难:/。

enter image description here

或者还有其他技术可以达到这个目的吗?

2 个答案:

答案 0 :(得分:4)

这是一个简单的算法:

  1. 对于棕色区域中的每个六边形H,迭代6个方向中的每个方向0≤dir< 6,并将D设为hex_neighbor(H, dir)
  2. 如果D为绿色,则在两者之间画一个边框。
  3. 警告:这不会将边框边缘连接到单个折线。

    我有a live demo的算法适用于任意数量的区域,以及绘制曲线的扩展。

    Screenshot of output of algorithm

答案 1 :(得分:1)

感谢Amit,与我们分享您的知识。您的算法更有效,更快捷。我必须做很少的修改才能使它在上面的例子中起作用。

  • 首先,如果十六进制在其中一个方向上没有邻居,则用null标记方向。

  • 第二个,在生成边缘时考虑具有null值的邻居。

否则,如果六角形在其中一侧没有邻居,则会留下空隙。

enter image description here

这是我用来绘制边缘的修改过的函数:

generateEdges: function( ctx ){
    var edges = [];
    var self = this;
    var neighbor = null;
    self.obs_arr.forEach( function( hex ){
        for( var dir = 0, nb_l = hex.neighbors.length; dir < nb_l; dir++ ){
            neighbor = hex.neighbors[dir];
            if(neighbor == null ||  hex.content != neighbor.content ){
                var p1 = self.point_add( hex.center, self.hex_corner_offset( dir ) );
                var p2 = self.point_add( hex.center, self.hex_corner_offset( (dir+1)%6 ) );
                edges.push( p1, p2 );
            }
        }
    });
    return edges;
},

现在一切都很完美。非常感谢Amit的帮助!