SVG <pattern> won't load when generated by Javascript [closed]

对着背影说爱祢 提交于 2019-12-14 00:22:30

问题


Updated question, based on a simpler test case:

I have a website using a <svg> graphic generated by a script. The stuff in the graphic is filled with svg patterns. So far, so good.

I now add a <pattern> element, using Javascript, to the patterns that are already in the graphic. I can easily do that, using methods like createElementNS, setAttribute and appendChild.

SVG pattern elements look like this:

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

and they're used like this:

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

Now: using Javascript, or the browser console, I can change a <path>'s fill attribute to use different patterns. That works fine for all the patterns that were in the page from the start, but it does not for patterns added later on. The SVG code itself is fine; saving it in a .svg and opening that up in the same browser shows the new pattern flawlessly.

Why can dynamically generated patterns not be used?


回答1:


Firstly, ensure you create an element using the namespaced document.createElementNS

e.g.

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

Secondly, only a reference within the 'style' attribute seemed to dynamically apply a pattern housed within '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" />



回答2:


Problem solved, this SO question helped me out. I had a typo in my SVG namespace declaration when I used createElementNS, so the pattern and path elements weren't recognized as "the real thing", but just as regular tags.

If you want to use Javascript to manipulate the SVG DOM tree, pay attention to this.



来源:https://stackoverflow.com/questions/6942830/svg-pattern-wont-load-when-generated-by-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!