【问题标题】:<image> in SVG: static image is visible, but dynamic is notSVG 中的 <image>:静态图像可见,但动态不可见
【发布时间】:2014-07-12 22:07:55
【问题描述】:

我的代码中有两个猴子:第一个是静态的(用 SVG 标签编写),没关系,但第二个(用 JS 生成)不可见,虽然标签中的代码在运行后完全相同.这怎么可能?我该如何解决?

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink">

  <image xlink:href="http://6962mnpm.blox.pl/resource/118392wtf.jpg"
    height="250px" width="250px" x="100px"></image>

</svg>

<script>
    var test = document.createElementNS("http://www.w3.org/2000/svg", "image");
    test.setAttribute("xlink:href",
        "http://6962mnpm.blox.pl/resource/118392wtf.jpg");
    test.setAttribute("height", "250px");
    test.setAttribute("width", "250px");
    test.setAttribute("x", "400px");
    document.querySelector("svg").appendChild(test);
</script>

【问题讨论】:

    标签: javascript image svg raster


    【解决方案1】:

    href 属性具有xlink 命名空间,因此您不能只使用setAttribute()。您必须使用setAttibuteNS()。试试这个:

    setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href",
                   "http://6962mnpm.blox.pl/resource/118392wtf.jpg");
    

    【讨论】:

      【解决方案2】:

      您不能使用setAttribute 添加命名空间属性,即使它在检查器中看起来正确。而是使用 setAttributeNS,如:

      setAttributeNS('http://www.w3.org/1999/xlink','href','http://6962mnpm.blox.pl/resource/118392wtf.jpg');
      

      现在猴子应该可以正常渲染了。

      var SVGDaddy = "http://www.w3.org/2000/svg";
      var TESTOBRAZKA = document.createElementNS(SVGDaddy, "image");
      with(TESTOBRAZKA) {
          setAttributeNS('http://www.w3.org/1999/xlink','href','http://6962mnpm.blox.pl/resource/118392wtf.jpg');
          setAttribute("height", "250px");
          setAttribute("width", "250px");
          setAttribute("x", "100px");
      }
      document.querySelector("svg").appendChild(TESTOBRAZKA);
      

      演示:http://jsfiddle.net/Palpatim/kGy5d/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-11
        • 1970-01-01
        • 2021-06-12
        • 2017-09-21
        • 1970-01-01
        • 1970-01-01
        • 2012-04-23
        • 1970-01-01
        相关资源
        最近更新 更多