如何利用项高度、项数及中点均匀设置元素的yAxis位置?
基于中点均匀分布数组元素的Y轴坐标计算
问题描述
我有一个包含0到n个元素的数组,每个元素带有height属性,已知Y轴区域的midPoint(中点),需要为每个元素设置yAxis(Y轴坐标),让所有元素整体均匀分布且以midPoint为中心。
示例代码:
let group = [ {id: 'A', height: 20, yAxis: 0}, {id: 'B', height: 20, yAxis: 0}, {id: 'C', height: 20, yAxis: 0} ]; let midPoint = 100;
我尝试过计算组的总高度除以元素数量,但不知道如何基于已确定的midPoint来设置位置?
解决方案
核心计算逻辑
要让元素组以midPoint为中心均匀排列,关键是先算出整个元素组的顶部起始坐标,再依次推导每个元素的yAxis:
- 计算总高度:累加所有元素的
height得到组的总高度(如果需要元素间的均匀间距,还要加上(元素数量-1)*间距值)。 - 计算起始坐标:整个元素组的顶部Y坐标 =
midPoint - 总高度 / 2,这个值就是第一个元素的yAxis。 - 依次赋值:从第二个元素开始,每个元素的
yAxis等于前一个元素的yAxis加上前一个元素的height(带间距的话再加间距值)。
无间距的代码实现
const calculateYAxis = (group, midPoint) => { const n = group.length; if (n === 0) return group; // 计算所有元素的总高度 const totalHeight = group.reduce((sum, item) => sum + item.height, 0); // 计算第一个元素的起始Y坐标 let currentY = midPoint - totalHeight / 2; // 为每个元素赋值yAxis return group.map(item => { const yAxis = currentY; currentY += item.height; return {...item, yAxis}; }); }; // 使用示例 let group = [ {id: 'A', height: 20, yAxis: 0}, {id: 'B', height: 20, yAxis: 0}, {id: 'C', height: 20, yAxis: 0} ]; let midPoint = 100; const resultGroup = calculateYAxis(group, midPoint); console.log(resultGroup); // 输出: // [ // {id: 'A', height: 20, yAxis: 70}, // {id: 'B', height: 20, yAxis: 90}, // {id: 'C', height: 20, yAxis: 110} // ]
带均匀间距的代码实现
如果需要元素之间保持固定间距,只需在总高度计算中加入间距总和:
const calculateYAxisWithGap = (group, midPoint, gap) => { const n = group.length; if (n === 0) return group; const totalHeight = group.reduce((sum, item) => sum + item.height, 0); const totalGap = (n - 1) * gap; const totalContentHeight = totalHeight + totalGap; let currentY = midPoint - totalContentHeight / 2; return group.map((item, index) => { const yAxis = currentY; // 最后一个元素不加间距 currentY += item.height + (index < n - 1 ? gap : 0); return {...item, yAxis}; }); }; // 使用示例(间距设为10) const resultGroupWithGap = calculateYAxisWithGap(group, 100, 10); console.log(resultGroupWithGap); // 输出: // [ // {id: 'A', height: 20, yAxis: 60}, // {id: 'B', height: 20, yAxis: 90}, // {id: 'C', height: 20, yAxis: 120} // ]
内容的提问来源于stack exchange,提问作者Alec Selinger
相关产品推荐
相关产品推荐

