I have some SVG files that specifies width
and height
as well as viewbox
like this:
None of the answers given here worked for me when I asked this back in 2009. As I now had the same issue again I noticed that using the <img>
tag and width together with an svg works fine.
<img width="400" src="image.svg">
Here is a PHP solution using QueryPath based on Jim Keller's answer.
Once QueryPath is loaded just pass your svg script to the function.
function scaleableSVG($svg){
$qp = qp($svg, 'svg');
$width = $qp->attr('width');
$height = $qp->attr('height');
$qp->removeAttr('width')->removeAttr('height');
$qp->attr('preserveAspectRatio', "xMinYMin meet");
$qp->attr('viewBox', "0 0 $width $height");
return $qp->html();
}
You can reach into the embedded svg using JavaScript:
var svg = document.getElementsByTagName('object')[0].\
contentDocument.getElementsByTagName('svg')[0];
svg.removeAttribute('width');
svg.removeAttribute('height');
Since your svg already has a viewBox, Firefox should scale the 576 pixel width in the viewBox to the 400 pixel width in your document. Other svgs might benefit from a new viewBox derived from the advertised width and height (these are often the same numbers). Other browsers might benefit from different svg tweaks.
You can add "preserveAspectRatio" and "viewBox" attributes to the <svg>
tag to accomplish this.
Open the .svg file in an editor and find the <svg>
tag.
in that tag, add the following attributes:
preserveAspectRatio="xMinYMin meet"
viewBox="0 0 {width} {height}"
Replace {width} and {height} with some defaults for the viewBox. I used the values from the "width" and "height" attributes of the SVG tag and it seemed to work.
Save the SVG and it should now scale as expected.
I found this information here:
https://blueprints.launchpad.net/inkscape/+spec/allow-browser-resizing
Let see. I had to refresh my memory on SVG, I haven't used it much these years.
From what I found today, it seems that if you specify dimension of objects without units, they have a fixed size (in pixels, I think). Apparently, then, there is no way to resize them when you resize the SVG (it only change the viewport/canvas size).
Unless, as pointed out, you specify the size of the SVG in percentage OR specify a viewBox (eg. viewBox="0 0 600 500").
Now, if you have no way to change the exported SVG, you are out of luck, I fear. What library do you use?
<body>
<div>
<object type="image/svg+xml" data="img/logo.svg">
<img src="img/logo.svg" alt="Browser fail" />
</object>
</div>
img/logo.svg ...
<svg
width="100%"
height="100%"
viewBox="0 0 640 80"
xmlns="http://www.w3.org/2000/svg"
version="1.1" />
This setup worked for me.