How to add double “new line” characters when using

2019-04-13 03:02发布

My app is dependent on the conversion of some HTML text elements into SVG elements, using Raphael.js.

The text in those HTML objects is given by the user, via a textarea input. Therefore, they can input new lines too. And those new lines need to be accounted for when creating the SVG. For this, I use the following code:

function replaceNL(text) {      
    return text.replace(/[\n\r]/g, "\n");
}

And when adding the SVG to the page:

var obj = paper.text(x,y,replaceNL(this.text));

The problem I've come across is that double (or more) line breaks strings (e.g. "\n\n") have the effect of just one in the .text() method. How can I overcome this?

1条回答
你好瞎i
2楼-- · 2019-04-13 03:23

This question does come up periodically... (http://stackoverflow.com/questions/12155954/nbsp-in-raphael-js)

If you modify your paper element to preserve spaces, all of the text elements within it will behave in the way you want. Do it like this:

paper.canvas.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space","preserve");

Here's the caveat: Raphael splits the strings passed to text on newlines, and inserts each segment into its own tspan. When the SVG rendering evaluates the tspans, it is sequencing each based on the bounding box of its predecessors. Because an empty tspan has a 0x0 bounding box, the newline -- though emitted -- is functionally invisible.

The rough workaround would be to emit "\n \n" -- the space character produces a bounding box, and thus causes the extra newline to be rendered. Sanity test here.

To control the height of the line breaks between tspans, you need to modify their dy attributes. Raphael does not support this out of the box, but it's easy to write a javascript function to set these manually. Here's the jquery method, given a Raphael text element textElement and your desired spacing, in pixels, as spacing:

$(textElement.node).find( 'tspan' ).attr( 'dy', spacing );
查看更多
登录 后发表回答