html - 在 RaphaelJS 中自动将文本换行到一定宽度?

标签 html css svg raphael

我目前正在尝试使用 RaphaelJS 添加一些动态添加的文本。我希望文本在 200 像素处中断,然后在下一行继续。就像您在 HTML 中有一个带宽度的常规 DIV 一样。

https://jsfiddle.net/qLvuztcy/

我试过类似的方法:

.text {
    width: 200px;
    max-width: 200px; //and this
}

但不幸的是,事实并非如此。有谁知道我怎么能做到这一点?我知道在文本中添加 \n 会换行,但我不确定如何实现我想要的。

最佳答案

I found an answer对于我稍微修改过的 Snap.svg。然而,它工作得很好。

function text(x, y, txt, max_width, element_class) {
    var abc = "abcdefghijklmnopqrstuvwxyzæøåABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ";
    var temp = rsr.text(50, 50, abc);
    temp.node.classList.add("text");
    var letter_width = temp.getBBox().width / abc.length;
    temp.remove();

    var heights = [];

    var loopLines = txt.split("\n");
    for (j = 0; j < loopLines.length; j++) {
        var words = loopLines[j].split(" ");
        var width_so_far = 0,
            current_line = 0,
            lines = [''];
        for (var i = 0; i < words.length; i++) {
            var l = words[i].length;
            if (width_so_far + (l * letter_width) > max_width) {
                lines.push('');
                current_line++;
                width_so_far = 0;
            }
            width_so_far += l * letter_width;
            lines[current_line] += words[i] + " ";
        }

        if (j > 0) {
            y += heights[j - 1];
        }

        lines = lines.join("\n");
        var t = rsr.text(x, y, lines);
        $(t.node).find("tspan").attr("dy", "1.2em");
        t.node.classList.add(element_class);
        heights.push(t.getBBox().height);
    }
}

需要 jQuery,因为我正在使用 jQuery 执行 find("tspan")(也可能,因为我也在其他地方使用它)。

我对其进行了修改,现在也支持在您的字符串中使用 \n

关于html - 在 RaphaelJS 中自动将文本换行到一定宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47328620/

相关文章:

css - 为什么 margin auto 不能使包含图像链接的 div 居中

css - Flex Grow(列)超过水平宽度

html - 调整包裹在 div 中的 svg 的大小,即包裹在 div 中

css - 防止 cssMin 删除 svg 样式

html - 导航栏下的 Twitter-Bootstrap 区域

html - 标题内带有 url 图片的表格

javascript - 嵌套 JQuery .click() 事件

javascript - 添加位置 :sticky to element causes jumpy behaviour on scroll

Javascript – 使用 Modernizr 媒体查询更改 SVG viewBox

html - 如何将大列分成较小的列