Javascript <;图像>;在SVG中:静态图像可见,但动态图像不可见

Javascript <;图像>;在SVG中:静态图像可见,但动态图像不可见,javascript,image,svg,raster,Javascript,Image,Svg,Raster,我的代码中有两个猴子:第一个是静态的(用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/11

我的代码中有两个猴子:第一个是静态的(用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>

var test=document.createElements(“http://www.w3.org/2000/svg“,”图像“);
test.setAttribute(“xlink:href”,
"http://6962mnpm.blox.pl/resource/118392wtf.jpg");
test.setAttribute(“高度”、“250px”);
test.setAttribute(“宽度”,“250px”);
test.setAttribute(“x”,“400px”);
document.querySelector(“svg”).appendChild(测试);

属性
href
具有
xlink
名称空间,因此不能仅使用
setAttribute()
。您必须使用
setAttibuteNS()
。请尝试以下方法:

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

href
属性具有
xlink
名称空间,因此不能只使用
setAttribute()
。您必须使用
setAttibuteNS()
。请尝试以下方法:

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

您不能使用
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);

演示:

您不能使用
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);
演示: