Reputation: 51
I'm trying to display an SVG scaled to the size of the object so a 600x600 svg get scaled to fit a 500x500 object or a 300x300 whatever. This all works just fine in FireFox but Safari and Chrome (Webkit) just crop the SVG
<div class="svg">
<object id="diagram" type="image/svg+xml" class="emb-diag" data="my.svg">
</object>
</div>
// Class method
setViewBox : function(objectSVG, containerSize, viewboxSize)
{
objectSVG.setAttribute("width", containerSize);
objectSVG.setAttribute("height", containerSize);
var svgDoc;
if ( typeof objectSVG.getSVGDocument != 'undefined')
{
svgDoc = objectSVG.getSVGDocument();
if (svgDoc == null)
{
svgDoc = objectSVG.contentDocument;
if (svgDoc == null)
{
return;
}
}
}
else
{
svgDoc = objectSVG.contentDocument;
if (svgDoc == null)
{
return;
}
}
var svgElem = svgDoc.documentElement;
if (svgElem)
{
svgElem.setAttribute("viewBox", "0 0 " + viewboxSize + " " + viewboxSize);
svgElem.setAttribute("preserveAspectRatio", "xMinYMin meet");
}
},
TheClass.setViewBox(document.getElementById("diagram"), 500, 600);
When debug in Safari this line
var svgElem = svgDoc.documentElement;
interrepts the svgElem variable as an HTMLHtmlElement as does Chrome
svgDoc: HTMLDocument
svgElem: **HTMLHtmlElement**
accessKey: ""
attributes: NamedNodeMap
baseURI: "about:blank"
childElementCount: 2
childNodes: NodeList[2]
children: HTMLCollection[2]
classList: DOMTokenList
className: ""
clientHeight: 500
clientLeft: 0
clientTop: 0
clientWidth: 500
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
...
Chrome does report the following
Resource interpreted as Document but transferred with MIME type image/svg+xml:
"file:///my.svg". jquery.min.js:2
(anonymous function) jquery.min.js:2
f.Callbacks.o jquery.min.js:2
f.Callbacks.p.fireWith jquery.min.js:2
e.extend.ready jquery.min.js:2
c.addEventListener.B
But I get that - but why? My Googling activities shed no light on the matter.
FireFox interrepts it as : As proper SVG DOM the whole SVG file can be expanded as you'd expect
Just preempt I've been down the route already that even worse both these lines both return null svgDoc = objectSVG.getSVGDocument(); svgDoc = objectSVG.contentDocument;
FireFox is fine Safari and Chrome don't scale
I can do it with an and scaling works but the svgDoc remains null but there's no access to the SVG DOM and that's what I want.
I've not tested the SVG inline variant but I really don't want to have to go down that route if at all possible.
If anybody out there has been down this path before me, thrashing through the undergrowth along the way, then your insights would be very much appreciated.
Upvotes: 2
Views: 3223
Reputation: 124006
You shouldn't try to access the contentDocument until the onload event of the <object>
element has fired. Try moving the TheClass.setViewBox call into the onload handler e.g.
<object onload="TheClass.setViewBox..."
Upvotes: 2