gpt4 book ai didi

javascript - 通过javascript获取SVG图形的大小

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:31 25 4
gpt4 key购买 nike

在html页面中添加一个svg图形,通常使用object标签这样包裹起来:

<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>

如果不在对象标签中使用宽度和高度属性,则 svg 将以全尺寸显示。通常我从 Open Graphics Library 获取 svg 文件进行测试。有什么方法可以使用 JavaScript 获取 svg 的大小吗?或者也许我应该只查看 svg xml 文件以找出顶部 svg 标签的大小?

最佳答案

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

只要 SVG 文件在同一个域中,就有可能访问 HTML:object 引用的 SVG DOM(否则这将是一个安全漏洞。如果你的对象标签有 id="myobj"你会做:

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 元素的宽度/高度:

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

请注意,这些属性可能是“100px”、“300”、“200em”、“40mm”、“100%”,因此您需要仔细解析它。

关于javascript - 通过javascript获取SVG图形的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/231679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com