Patricia
Patricia

Reputation: 95

How to draw non-scalable text in SVG with Javascript?

I'm using d3 library to create a svg graphic. The problem I have is when I resize the window. The whole graphic resizes meaning that texts (legend and axis) resize as well, to the point where it's unreadable. I need it to keep the same size when resizing.

I've been searching online and I found this solution:

var resizeTracker;
            // Counteracts all transforms applied above an element.
            // Apply a translation to the element to have it remain at a local position
            var unscale = function (el) {        

                var svg = el.ownerSVGElement;
                var xf = el.scaleIndependentXForm; 

                if (!xf) {
                    // Keep a single transform matrix in the stack for fighting transformations
                    xf = el.scaleIndependentXForm = svg.createSVGTransform();
                    // Be sure to apply this transform after existing transforms (translate)
                    el.transform.baseVal.appendItem(xf);
                }
                var m = svg.getTransformToElement(el.parentNode);
                m.e = m.f = 0; // Ignore (preserve) any translations done up to this point
                xf.setMatrix(m);                    
            };
            [].forEach.call($("text"), unscale);
            $(window).resize(function () {                                  
                if (resizeTracker) clearTimeout(resizeTracker);
                resizeTracker = setTimeout(function () { [].forEach.call($("text"), unscale); }, 0);
            });

And added it to my code, but it's not working. I debugged it and at this part of the code:

var xf = el.scaleIndependentXForm; 

It always returns the same matrix: 1 0 0 1 0 0 and the text keeps resizing as does the rest of the svg elements instead of keeping static.

Could anyone help me, please? Thanks in advance.

Upvotes: 1

Views: 234

Answers (1)

leegent
leegent

Reputation: 964

The same thing was happening to me with an SVG generated by SnapSVG until I noted that the example page on which this does work wraps its 'main' SVG tag in another SVG tag before using el.ownerSVGElement.ownerSVGElement rather than el.ownerSVGElement.

Wrapping my SVG in an 'empty' wrapper SVG (note style overflow:visible;) I had much better results!

Edit: oh, wait. Internet Explorer still isn't happy. Seems the author of the solution is aware...

Upvotes: 1

Related Questions