JavaScript 合并相交矩形
我需要一种方法,仅当矩形对象(具有 x,y,w,h 属性的对象)相交时才合并它们。例如:
merge([{x:0, y:0, w:5, h:5}, {x:1, y:1, w:5, h:5}])
将返回: [{x:0, y:0, w:6, h:6}]
merge([{x:0, y:0, w:1, h :1}, {x:5, y:5, w:1, h:1}])
将返回:[{x:0, y:0, w:1, h:1 }, {x:5, y:5, w:1, h:1}]
merge([{x:0, y:0, w:5, h:5}, {x :1, y:1, w:5, h:5}, {x:15, y:15, w:1, h:1}])
将返回:[{x:0 , y:0, w:6, h:6}, {x:15, y:15, w:1, h:1}]
如果两个矩形相交,则应用一个最小外接矩形替换这两个矩形矩形。合并后需要再次检查列表,以防新的 MBR 导致与其他矩形相交。对于我的一生,我无法弄清楚。
I need a way to merge an array of rectangle objects (objects with x,y,w,h
properties) only if they intersect. So for example:
merge([{x:0, y:0, w:5, h:5}, {x:1, y:1, w:5, h:5}])
would return: [{x:0, y:0, w:6, h:6}]
merge([{x:0, y:0, w:1, h:1}, {x:5, y:5, w:1, h:1}])
would return: [{x:0, y:0, w:1, h:1}, {x:5, y:5, w:1, h:1}]
merge([{x:0, y:0, w:5, h:5}, {x:1, y:1, w:5, h:5}, {x:15, y:15, w:1, h:1}])
would return: [{x:0, y:0, w:6, h:6}, {x:15, y:15, w:1, h:1}]
If two rectangles intersect, a minimum bounding rectangle should be replace the two rectangles. The list will need to be checked again after merging in case the new MBR causes intersection with other rectangles. For the life of me I can't figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定这是否有效,但我的脑海中浮现出类似的东西......
I'm not sure if this will work but off the top of my head something like...
这可以通过将问题建模为图表来解决。节点是矩形,每当其中任何两个节点之间存在交集时,我们就认为这两个节点通过边连接。
我们的目标是将矩形集分成直接或间接相互连接的组。这基本上是图的连接组件。这可以使用 广度优先搜索 或 深度优先搜索。
找到所有组件后,我们只需找到每个组件中所有矩形的最高左上角和最低右下角即可找到它们的边界框。
可以使用@Marcus' 答案中提供的函数来检查交集。
该过程的总体复杂度为 O(n^2),其中 n 是矩形的数量。
This can be solved by modelling the problem as a graph. The nodes are the rectangles, and whenever there is an intersection between any two of them, we consider that those two nodes are connected by an edge.
Our target is to divide the set of rectangles into groups that are connected, either directly or indirectly, with each other. This is basically a connected component of the graph. This can be found out using a breadth first search or a depth first search.
After all components are found, we just need to find the highest top left corner and the lowest bottom right corner of all the rectangles in each to find their bounding box.
Checking for intersection can be done using the function provided in @Marcus' answer.
The overall complexity of this procedure is O(n^2), where n is the number of rectangles.
如果有人需要完整的工作示例,这里是 repl 来玩 https://repl.it/@anjmao/合并矩形 和代码:
In case somebody needs fully working example here is repl to play https://repl.it/@anjmao/merge-rectangles and code: