如何添加双“换行" Raphael.js中使用`text`方法时使用的字符? [英] How to add double "new line" characters when using the `text` method in Raphael.js?

查看:252
本文介绍了如何添加双“换行" Raphael.js中使用`text`方法时使用的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用依赖于使用 Raphael.js 的一些HTML文本元素到SVG元素的转换.

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

这些HTML对象中的文本由用户通过textarea输入指定.因此,他们也可以输入新行.并且在创建SVG时需要考虑这些新行. 为此,我使用以下代码:

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");
}

在将SVG添加到页面时:

And when adding the SVG to the page:

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

我遇到的问题是,在(c0>)方法中,双(或多个)换行符字符串(例如"\ n \ n")的作用只有一个. 我该如何克服?

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?

推荐答案

这个问题确实会定期出现...(http://stackoverflow.com/questions/12155954/nbsp-in-raphael-js)

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");

这里是警告:Raphael在换行符上分割传递给text的字符串,并将每个段插入到自己的tspan中. SVG渲染评估tspan时,将根据其前任的边界框对每个tspan进行排序.因为空的tspan的边界框为0x0,所以换行符(尽管发出了)在功能上是不可见的.

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.

一个粗略的解决方法是发出"\ n \ n"-空格字符会产生一个边界框,从而导致多余的换行符被渲染.健全性测试此处.

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.

要控制tspan之间换行的高度,您需要修改其dy属性. Raphael不支持开箱即用,但是很容易编写一个javascript函数来手动设置它们.这是jquery方法,给出了Raphael文本元素textElement,并且您想要的间距(以像素为单位)为spacing:

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 );

这篇关于如何添加双“换行" Raphael.js中使用`text`方法时使用的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆