Search code examples
objectsvgscale

How to display SVG without any scaling


I have some code that generates diagrams in SVG. I want to display those in a web page. I want all the diagrams scaled at the original scale. There are many diagrams of varying sizes. The window I am displaying them in might change size, responsive to the browser size. But I do not want the SVG to be scaled. I want it to scroll instead.

I can ember the object tag in a div tag, and I can turn on the scroll bars for the div tag, but no matter what I do, the SVG is scaled to fit in the div.

If I knew the size of the image, I could force the canvas to be the same size. Is there any way to just say: bring in the SVG and don't do any scaling?

This same question was asked before but no answer.

Here is a sample svg file:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    viewBox="0 0 1191 971" 
    preserveAspectRatio="xMidYMid meet">
    <rect x="372" y="188" width="102" height="68" rx="10" 
        ry="10" style="stroke:blue"/>
    <svg x="372" y="188" width="102" height="68">
        <text>
            <tspan x="51" y="12">DTP</tspan>
        </text>
    </svg>
</svg>

But remember, this one is 1191x971 but others will be all different sizes. I would like it to display without scaling, no matter the size of the SVG diagram dimensions.

Here i the div tag I am placing this in, and I am using AngularJS to place the URL value into the object tag. In this case I am forcing the div to be 300x300, but that is because I want to test that the SVG is not scaled to this size.

<div style="height:300px;width:300px;overflow:scroll">
    <object type="image/svg+xml"  data="{{svgUrl}}">
    </object>
</div>

What I get with that is the 300x300 area appears with scroll bars, but the SVG image is scaled (shrunk) to fit in 300x300 area.


Solution

  • As it exists now, your SVG has been configured to be scaling/responsive. This is because of two things.

    1. It has a viewBox
    2. It has no width or height defined, so those attributes default to "100%". Meaning 100% of its container.

    If you want it to not scale, then you need give either the <svg>, or the <object>, a specific width. For example, if you want it to be rendered at 1:1, you would need to give it the same width and height as the viewBox:

    <svg width="1191" height="971"  ...>
    

    or

    <object width="1191" height="971"  ...>
    

    If you are able to alter the original SVGs, then that would probably be the simplest solution. Otherwise, you are going to need some JS. After the SVG has loaded, get a reference to the SVG element via the contentDocument property on the <object> element. From there you can get the viewBox width and height. Then use those to update the <object> width and height.