SVG get text element width

前端 未结 6 1825
误落风尘
误落风尘 2020-12-02 07:40

I\'m working on some ECMAScript/JavaScript for an SVG file and need to get the width and height of a text element so I can resize a re

6条回答
  •  孤城傲影
    2020-12-02 08:17

    How about something like this for compatibility:

    function svgElemWidth(elem) {
        var methods = [ // name of function and how to process its result
            { fn: 'getBBox', w: function(x) { return x.width; }, },
            { fn: 'getBoundingClientRect', w: function(x) { return x.width; }, },
            { fn: 'getComputedTextLength', w: function(x) { return x; }, }, // text elements only
        ];
        var widths = [];
        var width, i, method;
        for (i = 0; i < methods.length; i++) {
            method = methods[i];
            if (typeof elem[method.fn] === 'function') {
                width = method.w(elem[method.fn]());
                if (width !== 0) {
                    widths.push(width);
                }
            }
        }
        var result;
        if (widths.length) {
            result = 0;
            for (i = 0; i < widths.length; i++) {
                result += widths[i];
            }
            result /= widths.length;
        }
        return result;
    }
    

    This returns the average of any valid results of the three methods. You could improve it to cast out outliers or to favor getComputedTextLength if the element is a text element.

    Warning: As the comment says, getBoundingClientRect is tricky. Either remove it from the methods or use this only on elements where getBoundingClientRect will return good results, so no rotation and probably no scaling(?)

提交回复
热议问题