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

seb*_*n_k 7 javascript svg dynamic

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

我有一个网站使用<svg>脚本生成的图形.图形中的东西充满了svg图案.到现在为止还挺好.

我现在<pattern>使用Javascript 将一个元素添加到图形中已有的模式中.我可以很容易地做到这一点,利用类似的方法createElementNS,setAttributeappendChild.

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>
Run Code Online (Sandbox Code Playgroud)

他们像这样使用:

<path d="..." fill="url(#stripes)" />
Run Code Online (Sandbox Code Playgroud)

现在:使用Javascript,或者浏览器控制台,我可以改变<path>fill属性使用不同的图案.这工作正常,所有的人从一开始的页面模式,但它不是为后来添加上的图案.SVG代码本身很好; 将它保存在.svg中并在同一浏览器中打开它可以完美地显示新模式.

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

Ste*_*eve 7

首先,确保使用命名空间document.createElementNS创建元素

例如

document.createElementNS('http://www.w3.org/2000/svg','rect')
Run Code Online (Sandbox Code Playgroud)

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

例如

<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" />
Run Code Online (Sandbox Code Playgroud)