纯SVG/HTML/CSS实现的堆叠柱状图如何显示各分段的计数
实现方案
核心思路
直接在堆叠柱状图的每个分段矩形区域内嵌入SVG的<text>元素,通过计算每个分段的垂直偏移量定位文本,让数值居中显示在对应色块内即可,无需引入额外依赖。
具体实现步骤
- 第一步:和你当前生成分段矩形的Y轴定位逻辑保持一致,先计算每个堆叠分段的累计偏移量,确保文本和对应色块的位置匹配
- 第二步:对每个值大于0的分段,新增
<text>元素,设置x属性为柱状图宽度的一半实现水平居中,y属性为「当前分段Y轴偏移 + 当前分段高度/2 + 文本行高修正值」,保证文本垂直居中 - 第三步:设置
text-anchor: middle、dominant-baseline: middle两个CSS属性,简化居中对齐的计算逻辑,文本颜色可根据背景色块亮度调整为黑/白保证可读性
核心代码示例
以下为适配你给出的数据集的原生实现逻辑:
const categories = ['passed', 'skipped', 'failed', 'untested']; const barWidth = 100; // 替换为你实际的柱状图宽度 const barGap = 30; // 替换为你实际的柱子间距 const totalHeight = 200; // 替换为你实际的柱状图总高度 const maxValue = 100; // 数据集的最大值,用来做高度比例换算 const svg = document.querySelector('svg'); // 替换为你实际的SVG容器选择器 data.forEach((item, barIndex) => { let currentY = 0; // 累计Y轴偏移,和矩形绘制逻辑保持一致 categories.forEach(cate => { const value = item[cate]; if(value <= 0) return; // 值为0的分段不需要显示文本和色块 const segHeight = (value / maxValue) * totalHeight; // 原有绘制分段矩形的逻辑,保留你自己的样式配置即可 const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); rect.setAttribute('x', 50 + barIndex * (barWidth + barGap)); rect.setAttribute('y', currentY); rect.setAttribute('width', barWidth); rect.setAttribute('height', segHeight); svg.appendChild(rect); // 新增:绘制对应数值文本 const text = document.createElementNS("http://www.w3.org/2000/svg", "text"); text.setAttribute('x', 50 + barIndex * (barWidth + barGap) + barWidth / 2); text.setAttribute('y', currentY + segHeight / 2); text.setAttribute('text-anchor', 'middle'); text.setAttribute('dominant-baseline', 'middle'); text.setAttribute('fill', '#fff'); // 浅色背景可修改为#000保证可读性 text.textContent = value; svg.appendChild(text); currentY += segHeight; }) })
CSS补充配置
可以给文本增加字号配置,避免文字超出小尺寸的分段区域:
svg text { font-size: 12px; user-select: none; }
内容的提问来源于stack exchange,提问作者Aren Trot
相关产品推荐
相关产品推荐

