在数据可视化领域,D3.js作为基于Web标准的JavaScript库,能够通过SVG实现灵活的文字排版效果,当需要在图表中添加垂直排列的汉字时(如古籍排版、纵向坐标轴标签或特殊设计需求),可通过以下专业方法实现:
通过transform
属性实现单个字符的垂直堆叠:
const verticalText = d3.select("svg") .append("g") .attr("transform", "translate(100,50)"); verticalText.selectAll("text") .data("纵排文字示例".split("")) .enter() .append("text") .attr("x", 0) .attr("y", (d,i) => i * 24) // 字符间距24px .attr("transform", "rotate(90)") .text(d => d);
技术细节:每个字符单独渲染并垂直偏移,需注意中文字体的等宽特性可能影响对齐效果。
结合CSS3特性实现语义化竖排:
.vertical-text { writing-mode: vertical-rl; text-orientation: upright; font-family: "Noto Sans SC", sans-serif; /* 推荐思源黑体 */ }
d3.select("body") .append("div") .style("position", "absolute") .style("left", "200px") .style("top", "50px") .html("<div class='vertical-text'>CSS竖排效果</div>");
兼容性说明:需检测浏览器是否支持writing-mode
属性(IE10+部分支持)。
当需要自动换行时,建议使用第三方扩展库:
import { textWrap } from "d3-textwrap"; d3.select("svg") .append("text") .attr("x", 300) .attr("y", 100) .call(textWrap().bounds({ width: 20, // 每列宽度 height: 200 // 容器高度 })) .text("长文本自动换列示例,超过设定宽度将自动换列显示");
verticalText.on("mouseover", function() { d3.select(this).transition().duration(300).attr("opacity", 0.7); });
引用说明:本文实现方法参考自Scott Murray《Interactive Data Visualization for the Web》(O’Reilly 2017)及D3.js官方文档v7.0版,浏览器兼容性数据来自CanIUse最新统计报告。