不呈现从javascript创建的SVG图像对象

不呈现从javascript创建的SVG图像对象,javascript,image,dom,svg,clip-path,Javascript,Image,Dom,Svg,Clip Path,我尝试使用剪辑路径创建图像,但动态创建对象时,图像不会渲染 下面是代码示例,第一个SVG是从JS创建的,第二个是从Javascript创建的 <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1" id="parent"></svg> <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" v

我尝试使用剪辑路径创建图像,但动态创建对象时,图像不会渲染

下面是代码示例,第一个SVG是从JS创建的,第二个是从Javascript创建的

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1" id="parent"></svg>
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1">
    <clippath id="cut-off-bottom">
        <rect x="0" y="0" width="200" height="100" />
    </clippath>
    <image id="imgs" xlink:href="https://images.unsplash.com/photo-1473042904451-00171c69419d?auto=format&fit=crop&w=1375&q=80" clip-path="url(#clip)"></image>
</svg>

下面是一个示例:

您似乎把所有setAttribute/setAttributeNS调用都弄混了

  • setAttribute在空名称空间中设置属性,因此该用例不需要SetAttributes
  • 如果您有一个不在空命名空间中的属性,如xlink:href,则必须使用setAttributeNS
var\u svgNS='1〕http://www.w3.org/2000/svg';
var parent=document.getElementById('parent');
var clippath=document.createElements(_svgNS,'clippath');
setAttribute('id','clip');
父、子(clippath);
var rect=document.createElements(_svgNS,'rect');
rect.setAttribute('x','0');
rect.setAttribute('y','0');
rect.setAttribute('width','200');
rect.setAttribute('height','200');
clippath.appendChild(rect);
var imageElement=document.createElements(_svgNS,'image');
imageElement.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','https://images.unsplash.com/photo-1473042904451-00171c69419d?auto=format&fit=crop&w=1375&q=80');
setAttribute('clip-path','url(#clip');
parent.appendChild(imageElement)

你为什么要使用setAttributeNS?为什么你在不得不的时候不使用…上帝,我是瞎子。谢谢你的帮助
var _svgNS = 'http://www.w3.org/2000/svg';
var parent = document.getElementById('parent');

var clippath = document.createElementNS(_svgNS, 'clipPath');
clippath.setAttributeNS(null, 'id', 'clip');
parent.appendChild(clippath);

var rect = document.createElementNS(_svgNS, 'rect');
rect.setAttributeNS(null, 'x', '0');
rect.setAttributeNS(null, 'y', '0');
rect.setAttributeNS(null, 'width', '200');
rect.setAttributeNS(null, 'height', '200');
clippath.appendChild(rect);


var imageElement = document.createElementNS(_svgNS, 'image');
imageElement.setAttribute('xlink:href', 'https://images.unsplash.com/photo-1473042904451-00171c69419d?auto=format&fit=crop&w=1375&q=80');
imageElement.setAttribute('clip-path', 'url(#clip)');
parent.appendChild(imageElement);