21

I am using Raphael js to draw circled numbers. The problem is that each number has a different width/height so using one set of coordinates to center the text isn't working. The text displays differently between IE, FF, and safari. Is there a dynamic way to find the height/width of the number and center it accordingly?

Here is my test page:

http://jesserosenfield.com/fluid/test.html

and my code:

function drawcircle(div, text) { 
    var paper = Raphael(div, 26, 26); //<<
    var circle = paper.circle(13, 13, 10.5);
    circle.attr("stroke", "#f1f1f1");
    circle.attr("stroke-width", 2);
    var text = paper.text(12, 13, text); //<<
    text.attr({'font-size': 15, 'font-family': 'FranklinGothicFSCondensed-1, FranklinGothicFSCondensed-2'});
    text.attr("fill", "#f1f1f1");
}

window.onload = function () {
    drawcircle("c1", "1");
    drawcircle("c2", "2");
    drawcircle("c3", "3");
};

Thanks very much!

HandiworkNYC.com
  • 10,914
  • 25
  • 92
  • 154

4 Answers4

32

(Answer rewritten): Raphael.js centers text nodes both horizontally and vertically by default.

"Centering" here means that the x, y argument of paper.text() method expects the center of the text's bounding box.

So, just specifying the same x, y value as the circle should produce the desired result:

var circle = paper.circle(13, 13, 10.5);
var text = paper.text(13, 13, "10");

Example output

(jsFiddle)

Relevant source code:

ento
  • 5,801
  • 6
  • 51
  • 69
9

Maybe this:

var paper = Raphael(div, 26, 26); //<<
var circle = paper.circle(13, 13, 10.5);
circle.attr("stroke", "#f1f1f1");
circle.attr("stroke-width", 2);
var text = paper.text(0, 0, text); //<<
text.attr({'font-size': 15, 'font-family': 'FranklinGothicFSCondensed-1, FranklinGothicFSCondensed-2'});
text.attr("fill", "#f1f1f1");
text.translate((35 - text.getBBox().width)/2, (45 - text.getBBox().height)/2);
Jan Tojnar
  • 5,306
  • 3
  • 29
  • 49
3

Use this attribute: 'text-anchor':'start':

paper.text( x, y, text ).attr( {'text-anchor':'start'} );
Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
  • Thanks! This is so usefull. Had a lot of troubles aligning texts inside raphaels SVG, but thanks to this all my problems are gone! You rock :D – taxicala Nov 10 '14 at 14:48
0

The Rotating Text Exactly example (listed in the right-hand column of the page, or here in github), discusses putting text in a precise position, along with, as usual, extra steps required to make things work in IE.

It does find a bounding box for the text; I imagine it is straightforward to move the text by half the bounding box as Jan suggested.

Clinton Blackmore
  • 2,427
  • 2
  • 24
  • 31