views:

171

answers:

1

Does anyone know how to attach a text to a path in Raphaël? Something like http://www.w3.org/TR/SVG11/images/text/toap02.svg I know that jQuery SVG can do that, but I can't find an easy way to do this by using Raphaël js. I want to attacht this text to a bezier curve and move it.

+1  A: 

There are 2 ways to do this.

  1. The easier way is to make use of the Raphael .print() method. This can turn text into paths. Each character gets its own path. Then you can iterate over each character and move and rotate it appropriately using .translate() and .angle().

  2. The harder way is to implement text on path for both SVG and VML for a Raphael .text().

Here's a quick and rough start for Method 1 with no rotation using .print() and this font:

window.onload = function() {
    var i, newP,
        R = Raphael("canvas",500,400),

          // Create our set of letter paths
        t = R.print(100, 0, "this is a test", R.getFont("whoa"), 30),

          // Create the path to follow
        p = R.path("M 50 100 C 100 50 150 0 200 50 C 250 100 300 150 350 100" +
                   " C 400 50 450 50 450 50").attr("stroke", "none"),
        pLen = p.getTotalLength(), // Length of path to follow
        tLen = t.length,           // Number of characters
        oneL = pLen/tLen;          // Average length of 1 character
          // You can also use .getBBox() for each character instead       

      // Position each character
    for (i = 0; i < tLen; i++) {

          // Get x,y of the path to follow
        newP = p.getPointAtLength(i * oneL);

          // Move the letter
        t[i].translate((i * oneL)-newP.x, newP.y); 
        t[i].attr("fill", Raphael.getColor());
    }
};​

Try it out with this jsFiddle

Note: The above code is very rough and has some important positioning problems, but I think the general approach is the way to go for putting text on a path with Raphael.

Peter Ajtai