Multi-line text box

One feature that I know a lot of people, myself included, would like in SVG is a multi-line text box, so I've made one. You can see the result below and download the file at the bottom of the page. In Chrome, at least, you should see two multi-line blocks of text and two rectangles of empty space. In Firefox or a program like Inkscape you will see two long lines of text. I'm trying to find a simple way to get it to work in Firefox.

The SVG contains two texts element like this:

<text x="5" y="20" onload="create_multiline(evt, 280)">Alice was beginning...</text>
<text x="160" y="155" onload="create_multiline(evt, 200)">So she was considering...</text>

As you can see, both elements call a function called create_multiline() when they load (which is what Firefox doesn't do). The parameters passed are evt, which allows the function to know which element called it, and a number which defines the width of the box.

The createmultiline function does the following:

Split text at spaces to get an array of words

var words =' ');

Remove the words from the original text element = '';

Add a tspan element containing the first word to the text element

var tspan_element = document.createElementNS(svgNS, "tspan");
var text_node = document.createTextNode(words[0]);

Add words to the tspan element one by one

for(var i=1; i<words.length; i++) { += " " + words[i];

If the width is exceeded...

if (tspan_element.getComputedTextLength() > width) {

Remove the previous word =, len);

Add a new tspan element with that word

var tspan_element = document.createElementNS(svgNS, "tspan");
tspan_element.setAttributeNS(null, "x", start_x);
tspan_element.setAttributeNS(null, "dy", 18);
text_node = document.createTextNode(words[i]);

Start adding words one by one again (continue loop).

multiline_text.svg2.6 KB



Isn't it possible to just create a <text class="multiline" value="280" /> to avoid Firefox from not loading it? Current version of (12.0) still doesn't support onload :-(

I haven't tested it right now, but would this also support xlink:href? Otherwise it may be an option to just have the script read an external .txt file and fill it in. As such it may need a height declaration as well and a way to add a carriage return for paragraphing.

Post new comment

The content of this field is kept private and will not be shown publicly.