SVG< pattern>由JavaScript生成时不会加载 [英] SVG <pattern> won't load when generated by Javascript
问题描述
更新的问题,基于一个更简单的测试用例:
我有一个网站使用< svg> ;
由脚本生成的图形。图形中的东西充满了svg模式。到目前为止,这么好。
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.
我现在使用Javascript添加一个< pattern>
元素已经在图形中。我可以使用诸如 createElementNS
, setAttribute
和 appendChild
。
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模式元素如下所示:
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>
它们的用法如下:
<path d="..." fill="url(#stripes)" />
现在:使用Javascript或浏览器控制台,我可以更改一个 ; path>
的填充
属性以使用不同的模式。这对于从一开始就在页面中的所有模式都可以正常工作,但是对于稍后添加的模式,它不会不。 SVG代码本身很好将其保存在.svg中,并在同一浏览器中打开,完美无缺地显示新的模式。
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?
推荐答案
首先,确保使用命名空间 document.createElementNS
Firstly, ensure you create an element using the namespaced document.createElementNS
例如
document.createElementNS('http://www.w3.org/2000/svg','rect')
其次,只有style属性中的引用似乎动态地应用在'defs'中的模式
Secondly, only a reference within the 'style' attribute seemed to dynamically apply a pattern housed within '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" />
这篇关于SVG< pattern>由JavaScript生成时不会加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!