SVG won't load when generated by Jav

2019-04-07 01:35发布

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?

2条回答
ゆ 、 Hurt°
2楼-- · 2019-04-07 02:04

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" />
查看更多
smile是对你的礼貌
3楼-- · 2019-04-07 02:06

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.

查看更多
登录 后发表回答