Raphael JS and Text positioning?

29,964

Solution 1

Resolved!

By using the following

paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);

it now aligns text on the left.

Solution 2

Text-anchor property for text method is set to 'middle' by default.

If you want to left align it then change text-anchor in attributes for the object:

var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!").attr({'text-anchor': 'start'});

Solution 3

I know you didn't say you need to vertical align it to top, but if you want to use paper.text instead of paper.print... and would like to vertical align to be top.

Try this:

function alignTop(t) {
    var b = t.getBBox();
    var h = Math.abs(b.y2) - Math.abs(b.y) + 1;

    t.attr({
        'y': b.y + h
    });
}

And just pass the Raphael text object to it. It will top align it for you. and just call that function

Share:
29,964

Related videos on Youtube

RadiantHex
Author by

RadiantHex

hello! :)

Updated on October 19, 2020

Comments

  • RadiantHex
    RadiantHex over 3 years

    I'm trying to position text within the SVG canvas, by supplying x, y coordinates

    var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
    

    but does not position the text like all other objects...

    x, y coordinates specify the center of the object! Not the "left and top most" pixel!


    I would like to "left align" the text along a line, same as standard HTML.

    Help would be very much appreciated.

  • MKroehnert
    MKroehnert about 13 years
    paper.print() is not the same as paper.text() because print() returns a set of objects where each object is a path resembling a character. See @dasha salo's answer for the correct "text" solution. Unfortunately there is no vertical alignment property currently.
  • karlisup
    karlisup over 11 years
    As You said @RadiantHex didn't ask for vertical align, but at least it helped me, thanks!
  • pp19dd
    pp19dd almost 11 years
    Probably the 4th time for me to look this question up and get your answer. First to upvote. ;)
  • john-jones
    john-jones over 10 years
    but is there a top anchor?
  • streetlogics
    streetlogics over 9 years
    Thank you good sir for the t.attr({y:}) reference, you saved my butt! :)