Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 917
sk29910 Avatar asked Aug 04 '11 14:08

sk29910


1 Answers

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" />
like image 59
Steve Avatar answered Nov 05 '22 02:11

Steve