通过JavaScript获取SVG图形的大小 [英] Get size of SVG graphics by javascript

查看:365
本文介绍了通过JavaScript获取SVG图形的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在html页面中添加svg图形,通常使用对象标记像这样包装它:

To add a svg graphics in html page, it is common to use object tag to wrap it like this:

<object id="svgid" data="mysvg.svg" type="image/svg+xml" 
  wmode="transparent" width="100" height="100">

this browser is not able to show SVG: <a linkindex="3"
href="http://getfirefox.com">http://getfirefox.com</a> 
is free and does it!
If you use Internet Explorer, you can also get a plugin: 
<a linkindex="4" href="http://www.adobe.com/svg/viewer/install/main.html">
http://www.adobe.com/svg/viewer/install/main.html</a>

</object>

如果您未在object标签中使用width和height属性,则svg将以完整尺寸显示.通常,我会从Open Graphics Library获取svg文件进行测试.有没有办法通过使用JavaScript来获取svg的大小?或者,也许我应该只查看svg xml文件以从顶部的svg标签中找出大小?

If you do not use width and height attributes in the object tag, the svg will be displayed in full size. Normally I get svg files from Open Graphics Library for testing. Is there any way to get svg's size by using JavaScript? Or maybe I should just look at the svg xml file to find out the size from the top svg tag?

推荐答案

请参见 http://dev.opera.com/articles/view/svg-evolution-not-revolution/?page=2

只要SVG文件位于同一域中,就可以访问HTML:object引用的SVG DOM(否则这将是一个安全漏洞.如果您的对象标记具有id ="myobj",会做到:

It is possible to get access to the SVG DOM referenced by an HTML:object as long as the SVG file is on the same domain (otherwise this would be a security vulnerability. If your object tag has id="myobj" you would do:

var obj = document.getElementById("myobj"); // reference to the object tag
var svgdoc = obj.contentDocument; // reference to the SVG document
var svgelem = svgdoc.documentElement; // reference to the SVG element

然后,您可以通过以下方式访问svg元素的宽度/高度:

Then you can get access to the svg element's width/height by:

svgelem.getAttribute("width")
svgelem.getAttribute("height")

请注意,这些属性可能是"100px","300","200em","40mm","100%"之类的,因此您需要仔细分析.

Note that these attributes may be things like "100px", "300", "200em", "40mm", "100%" so you need to carefully parse it.

这篇关于通过JavaScript获取SVG图形的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆