views:

613

answers:

1

I built some shapes using Raphael, and now I wanted to put some text into them. But, it seems, from the examples, that a text node can only be attached to the paper and not svg shapes?

Is it possible to create multiple shapes with different text inside?

The example I was using was:

paper.text(50, 50, "Raphaël\nkicks\nbutt!");
+3  A: 

In Raphael, all drawing elements (shapes, lines, text, etc) only exist as part of encompassing paper object. There is no hierarchal structure to them per se. Nor is there a text attribute for any of these shapes unfortunately. So a text node cannot be 'attached' to a shape element in the proper sense.

However you can use a 'Set' node to give the appearance of a text node being attached to a shape. A Set is an array of elements where transformations (translation, rotation, etc) can be applied to all members in a single operation. So if you made a set containing one rectangle and one text node, you can them treat that set element as a single entity. You can then create a second instance of that set and treat it differently. So while all text elements still technically belong to the paper object, they behave (and appear) like they belong to the rectangle.

For Example:

var paper = Raphael(0, 0, 400, 400);
for (var i = 0; i < 10; i++)
{
    var group = paper.set();
    group.push(paper.rect(10, 10, 50, 20));
    group.push(paper.text(35, 18, "Hello"));

    group.translate(Math.random() * 350, Math.random() * 380);
    group.rotate(Math.random() * 90);
}

As a different approach, I've also had reasonable success with creating large quantities of separate paper objects on a page. But that's probably not where you want to go.

Nicholas