11

我们正在尝试使用 javascript 将剪贴路径用于折线。我们尝试编写一个运行良好的示例 HTML 代码:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="parent">
    <clippath id="cut-off-bottom">
        <rect x="0" y="0" width="200" height="100" />
    </clippath>
    <circle cx="100" cy="100" r="100" clip-path="url(#cut-off-bottom)" />
</svg>

这绝对没问题。

但是当我们尝试使用 javascript 生成相同的代码时,它不起作用:

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

circle = document.createElementNS(_svgNS, 'circle');
circle.setAttributeNS(null, 'cx', '100');
circle.setAttributeNS(null, 'cy', '100');
circle.setAttributeNS(null, 'r', '100');

clippath = document.createElementNS(_svgNS, 'clippath');
clippath.setAttributeNS(null, 'id', 'clip');

r = document.createElementNS(_svgNS, 'rect');
r.setAttributeNS(null, 'x', '0');
r.setAttributeNS(null, 'y', '0');
r.setAttributeNS(null, 'width', '200');
r.setAttributeNS(null, 'height', '100');


clippath.appendChild(r);

circle.setAttributeNS(_svgNS, 'clip-path', 'url(#clip)');
parent.appendChild(clippath);
parent.appendChild(circle);

任何人都可以帮助我们找到上述代码的问题...

提前致谢。

4

3 回答 3

20

经过一段时间的摆弄,事实证明 SVG 非常区分大小写,并且clippath元素需要是一个clipPath元素。

见工作小提琴:http: //jsfiddle.net/F4mq9/2/

然而,静态样本起作用非常奇怪。

于 2013-10-08T04:57:00.767 回答
2

您将 的 设置id<clippath>clip但随后将clip-path="url(#clippath). 您需要匹配id您设置的属性。

演示:http: //jsfiddle.net/uMe4s/7/

我已经对您的一些代码进行了修改(在创建元素后立即添加元素,而不是在末尾添加元素)。这对解决方案没有影响。

于 2013-10-08T03:59:53.503 回答
0

老问题,但是在批准的修复中没有提到修复。它不起作用的原因是由于 clippath 属性上的命名空间。就像在 jsfiddle 中一样,命名空间 url 应该设置为null.

于 2020-07-06T08:58:17.467 回答