
批注定位自适应问题求解
在开发批注功能时,我们遇到了一个批注间距自适应的问题。批注间距分为两种格式:
- 批注间隔远:批注离文本很近,就近原则显示。
- 批注紧挨着:批注之间不会相互重叠,自适应紧挨在一起。
用户的需求是创建批注时自动定位 Y 轴位置,同时防止出现批注重叠的情况。
解决思路
采用,统计每个批注的顶部位置和高度,并使用最大值函数计算出每个批注的当前顶部位置。这个算法优化后类似于瀑布流,但在计算过程中加入了 Math.max 函数。
数据结构:
[
{top: 100, height: 200},
{top: 800, height: 200},
{top: 820, height: 200},
{top: 1020, height: 200},
]
登录后复制
示例代码:
arr = [
{top: 100, height: 200},
{top: 800, height: 200},
{top: 820, height: 200},
{top: 1020, height: 200},
{top: 1430, height: 180},
]
arr.reduce((s, n, i) => {
n.currentTop = Math.max(n.top, (s.currentTop || s.top) + s.height)
return n
})
console.log(arr)
登录后复制
计算结果如下:
[
{top: 100, height: 200, currentTop: 100},
{top: 800, height: 200, currentTop: 1020},
{top: 820, height: 200, currentTop: 1040},
{top: 1020, height: 200, currentTop: 1240},
{top: 1430, height: 180, currentTop: 1430},
]
登录后复制
通过这个算法,我们可以得到批注的正确 Y 轴位置,并避免批注重叠的情况。
以上就是如何利用算法实现批注间距自适应,防止批注重叠?的详细内容,更多请关注米云其它相关文章!
