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

SVG Image object created from javascript is not rendered

我正在尝试创建一个带有剪辑路径的图像,但是当动态创建对象时,图像没有被渲染。

这是代码示例,第一个 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>

和 JS:

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

这里有一个例子:https://jsfiddle.net/n8pzo52q/

您的 setAttribute/setAttributeNS 电话似乎都搞混了。

  • setAttribute 在 null 命名空间中设置属性,因此您不需要为该用例设置 setAttributeNS。
  • 如果您有一个不在 null 命名空间中的属性,例如 xlink:href,那么您必须使用 setAttributeNS。

var _svgNS = 'http://www.w3.org/2000/svg';
var parent = document.getElementById('parent');

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

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


var imageElement = document.createElementNS(_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');
imageElement.setAttribute('clip-path', 'url(#clip)');
parent.appendChild(imageElement);
<svg id="parent"></svg>