如何确定 SVG 文本框宽度或在“x”个字符后强制换行?


使用 getBBox() 函数并将一个单词一次添加到文本对象中。当过宽时,需要添加换行符。

var a = Raphael(500, 500);
var b = a.text(100, 100).attr('text-anchor', 'start');
var maxWidth = 100;
var content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec semper mauris. Sed gravida augue feugiat nulla ultrices efficitur. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed sit amet lobortis eros, et lobortis diam. Aenean arcu velit, condimentum eu lacus in, dignissim bibendum odio. Mauris ultricies nunc et lorem bibendum dignissim. Ut porttitor purus vitae diam efficitur ultrices. Integer dignissim efficitur lorem, non vehicula diam scelerisque at ";
var w = content.split(" ");
var tempText = "";

for (var i = 0; i < w.length; i++) {
   b.attr("text", tempText + " " + words[i]);
   if (b.getBBox().width > maxWidth) {
      tempText += "
" + words[i];    } else {       tempText += " " + words[i];    } } b.attr("text", tempText.substring(1));

更新于: 2020-01-27

182 次浏览

提升你的 职业

完成课程,获得认证

开始学习
广告