批注定位自适应问题求解
在开发批注功能时,我们遇到了一个批注间距自适应的问题。批注间距分为两种格式:
用户的需求是创建批注时自动定位 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 轴位置,并避免批注重叠的情况。
以上就是如何利用算法实现批注间距自适应,防止批注重叠?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号