I am creating a rectangle element which I want to later use as a tooltip on an SVG circle element. Right now, I am trying to think of some logic to set the height and width of the rectangle element which should change according to the lines of text it contains.. I am simply creating a Raphael text element and translating it on the rectangle so that it appears as if the rectangle ‘really’ contains the text. (This is because I am not supposed to use any third-party tooltip plugin, neither can I create a and modify it using jQuery. Neither can I use gRaphael. I am supposed to use only Raphael rectangle element as the tooltip.)
Here’s what I am doing –
var tipText = "Asoo ok m ml palksksk feesf k\nWeek:X-VAL\nRank:Y-VAL";
//splitting tipText for "\n"
var tipText_seperate = tipText.split("\n");
var tipText_seperate_len = tipText_seperate.length;
var line_len = [];
for(var i=0;i<tipText_seperate_len;i++){
line_len[i] = tipText_seperate[i].length;
}
var a = Math.max.apply(Math, line_len);//getting the length of largest line
//setting the width and height of the rectangle
var box = {};
box.width = (a*5)+5;
box.height = tipText_seperate_len*25;
var c = {};
c.x = 10;
c.y = 10;
c.r = paper.rect(c.x,c.y,box.width,box.height,5).attr({fill:'#000000', opacity:0.7});
c.t = paper.text(c.x,c.y,tipText).attr({fill:'#FFFFFF'});
c.t.transform("t"+box.width/2+","+box.height/2);
Now the size of rectangle gets adjusted for some lines of text, while for some it doesn’t. In that case I have to change the value of box.width which does not seem correct. Is there any efficient and logically correct way to achieve this? Please Help…
The trick is to create the text element and use
getBBoxto get the bounding box of the text element, which provides the dimensions as well asxandyvalues.Here’s an example and demo.