【问题标题】:Chrome does not resize SVG imageChrome 不会调整 SVG 图像的大小
【发布时间】:2011-05-07 13:31:48
【问题描述】:

我想读入一个 SVG 文件,确定它的宽度和高度以便对其进行缩放。目前,我的代码如下所示:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <style type="text/css" media="all">@import "style/style.css";</style>
  <meta name="svg.render.forceflash" content="false" />
  <script src="svg.js" data-path="svgweb/src/"></script>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js">   </script>
  <script type="text/javascript">
    $(window).load(function() {
      function loadContent(){
        /*  SVG  */
        var svg = document.getElementById('myimage')

        /*  Adapt size of SVG */
        try {
      SVGDoc = svg.contentDocument;
    } catch (Err) {
      SVGDoc = svg.getSVGDocument;
        }
        var root = SVGDoc.documentElement;
        if (root.attributes['width'] != null) {
        var width = root.attributes['width'].nodeValue;
        width = width.substring(0, width.length - 2);
        width = (width * 1.25);
        var height = root.attributes['height'].nodeValue;
        height = height.substring(0, height.length - 2);
        height = (height * 1.25);
        svg.width = width;
        svg.height = height;
      }
</script>
</head>
<body>
  <div id="map">
    <!--[if IE]>
    <object id="myimage" src="images/myimage.svg" classid="image/svg+xml">
    <![endif]-->
    <!--[if !IE]>-->
    <object id="myimage" data="images/myimage.svg" type="image/svg+xml">
    <!--<![endif]-->
    </object>
  </div>
</body>
</html>

此代码在 Firefox 中运行良好(尽管可以在很短的时间内看到调整大小)。但是,Chrome 中的开发人员工具 nags:Uncaught TypeError: Cannot read property 'documentElement' of undefined for the line "var root = SVGDoc.documentElement;"。此外,Chrome 不会调整图像大小。

我找不到适用于这两种浏览器的解决方案。

【问题讨论】:

    标签: javascript firefox google-chrome svg


    【解决方案1】:

    首先,getSVGDocument() 是一个方法,而不是一个属性。你必须调用它:

    SVGDoc = svg.getSVGDocument();
    

    其次,SVGDoc 本身应该在某处声明:

    var SVGDoc;
    

    第三,Chrome 的same origin policydoes not likefile: 协议。您必须提供 SVG 图像,而不是从本地文件中读取它们。

    【讨论】:

    • 非常感谢您的指正。但是,Chrome 仍然抱怨:Uncaught TypeError: Cannot read property 'rootElement' of undefined
    • @labrassbandito,看起来很像Chromium Bug #29296。你的 Chrome 是最新的吗?
    • 我的版本是 7.0.517.41 (62167) Ubuntu 10.10。此外,我读到错误消息仅在通过 file:// 加载 SVG 时出现在本地。这似乎是真的,因为代码可以按预期在线工作。奇怪的。不幸的是,我错过了说明这一事实的网站。尽管如此,我面临着调整大小的问题。仅在 Firefox 中,SVG 会自动调整大小。
    • SVGDocument 继承了Document 接口,该接口具有documentElement。见w3.org/TR/SVG11/struct.html#InterfaceSVGDocument。所以调用documentElement是没有问题的。
    • @Erik,谢谢,我不知道。同源策略也适用于documentElement,这也是我们首先进入catch 块的原因。答案已更新。
    猜你喜欢
    • 2013-07-13
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    相关资源
    最近更新 更多