Trying to get the width of selected text in Raphael

So, I'm looking to get the size of a text string in Raphael, and I can't do it. Although the documentation states that

.attr('width');

is an option ... and I cannot set the width.

Here is FIDDLE

This is what I tried ... plus other rough ways (even using jQuery)

var page = Raphael("drawing_board");

    // start, move, and up are the drag functions
    start = function () {
        // storing original coordinates
        this.ox = this.attr("x");
        this.oy = this.attr("y");
        this.attr({opacity: .5});
        console.log( this.attr('width') ); //THIS IS WHERE I AM TRYING TO GET THE WIDTH
    },
    move = function (dx, dy) {
        // move will be called with dx and dy

            nowX = Math.min(600, this.ox + dx);
            nowY = Math.min(400, this.oy + dy);
            nowX = Math.max(0, nowX);
            nowY = Math.max(0, nowY);
            this.attr({x: nowX, y: nowY });

    },
    up = function () {
        // restoring state
        this.attr({opacity: 1});

    };   

    page.text(200, 50, "TEXT 1").attr({ cursor: "move", 'font-size': 16  , fill: '#3D6AA2'}).drag(move, start, up);
    page.text(200, 200, "TEXT 2").attr({ cursor: "move", 'font-size': 16  , fill: '#3D6AA2'}).drag(move, start, up);

Maybe I need to use something other than

this.attr('width' : 30); //To Set
this.attr('width'); //To Get
+5
source share
3 answers

You can use:

this.node.getBBox().width

this.node→ gets the SVG element associated with the Raphael element
getBBox()→ bounding box

You can also use the Raphael method getBBox:

this.getBBox().width

Your approach does not work because the svg text element does not have a width attribute.

+10

this.getBBox() - RaphaelJS bbox, x y x1 x2 width height . -, .

+3

SVG Text elements do not have an attribute width. Check it out in the w3c SVG specification: http://www.w3.org/TR/SVG/text.html#TextElement There are no widthattributes in the list, so you cannot set it.

But we could get the widthDOM element using jQuery. This can be done first by returning a reference to the DOM element and passing it to the constructor jQuery, then using the function width(). Here's the updated fiddle: http://jsfiddle.net/Rmegm/8/

0
source

All Articles