由Javascript </pattern>生成时,不会加载SVG <pattern>

时间:2011-08-04 14:03:44

标签: javascript dynamic svg

更新的问题,基于更简单的测试用例:

我有一个网站使用脚本生成的<svg>图形。图形中的东西充满了svg图案。到目前为止,非常好。

我现在使用Javascript将<pattern>元素添加到图形中已有的模式中。我可以使用createElementNSsetAttributeappendChild等方法轻松完成此操作。

SVG模式元素如下所示:

<defs>
<pattern id="stripes" width="6" height="6" patternUnits="userSpaceOnUse">
<svg:path d="M 0 0 L 10 0 L 10 1 L 0 1 Z" fill="red" width="6" height="6" id="stripepimage"></svg:path>
</pattern>
</defs>

他们就像这样使用:

<path d="..." fill="url(#stripes)" />

现在:使用Javascript或浏览器控制台,我可以更改<path>的{​​{1}}属性以使用不同的模式。这适用于从一开始就在页面中的所有模式,但对于稍后添加的模式,。 SVG代码本身很好;将它保存在.svg中并在同一浏览器中打开它可以完美地显示新模式。

为什么不能使用动态生成的模式?

2 个答案:

答案 0 :(得分:7)

首先,确保使用命名空间 document.createElementNS

创建元素

e.g。

document.createElementNS('http://www.w3.org/2000/svg','rect')

其次,只有'style'属性中的引用似乎动态应用'defs'中的模式

e.g。

<defs>
    <pattern id="patternTest1" width="10" height="10" patternUnits="userSpaceOnUse">
        <path d="M10,0 L10,10 L0,10" fill="none" stroke="#E9E9E9" stroke-width="1" shape-rendering="crispedges" vector-effect="non-scaling-stroke"/>
    </pattern>
</defs>

<rect id="test" x="10" y="10" width="250" height="250" style="fill: url('#patternTest1');" vector-effect="non-scaling-stroke" stroke-width="1" stroke-dasharray="none" stroke="#000000" />

答案 1 :(得分:0)

问题解决了,this这个问题帮助了我。当我使用createElementNS时,我的SVG名称空间声明中出现了拼写错误,因此模式和路径元素不会被识别为“真实的东西”,而是像常规标签一样。

如果您想使用Javascript来操纵SVG DOM树,请注意这一点。