img src = svg在同一个文档中 [英] img src=svg in the same document
问题描述
我有内嵌SVG模式。我需要两种不同的页面布局 - 一种用于媒体打印,另一种用于浏览器。我正在动态创建#svgCanvas中的所有内容,我需要它出现在我的打印布局的底部。
I have inline SVG with patterns. I need two different page layouts - one for "media print" another one for browsers. I am creating everything in #svgCanvas dynamically and I need it to appear at the bottom of my print layout.
我的第一个想法是克隆整个svg,但后来我得到了具有相同ID的东西,Firefox和Edge对它真的很不满。有什么方法可以达到这个目的?
My first idea was to clone whole svg, but then I ended up with things having same ID's and Firefox and Edge got really upset about it. What are the alternatives to achieve this?
我看过svg到html5画布转换,但由于某种原因,这对我来说并没有真正起作用所以我可能有另一种更简单的方式,如下面的那个?我知道可以这样做:
I had a look at doing svg to html5 canvas conversion but for some reason that did not really work out for me so I though maybe there is another easier way like the one below? I know it is possible to do something like this:
<img src="external.svg">
所以我认为我应该能够对内联svg做同样的事情。
so thought I should be able to do the same with inline svg.
<span class="media-print-only">
some stuff
<img src="#svgCanvas">
</span>
<span class="no-media-print">
some more stuff
<svg id="svgCanvas">
<defs> some <patterns> </defs>
some lines and rectangles that are using patterns in defs
</svg>
again more stuff
</span>
推荐答案
您可以使用使用
为此目的的元素。当您使用 id
创建SVG图形时,您可以使用使用
元素在任何地方引用它,就像这样。
You can use use
element for this purpose. When you create SVG graphic with id
, you can refer it in any place by using use
element, like this.
<span class="media-print-only">
<div class="svg-container">
<svg width="200px" height="200px">
<use xlink:href="#svgCanvas"/>
</svg>
</div>
</span>
<span class="media-no-print">
<div class="svgRealPlace">
<svg width="200px" height="200px">
<use xlink:href="#svgCanvas"/>
</svg>
</div>
</span>
<!--defining base SVG graphic-->
<svg width="0" height="0">
<svg id="svgCanvas" width="200px" height="200px">
<defs>
<pattern id="pattern" width="10" height="10" patternUnits="userSpaceOnUse">
<circle cx="5" cy="5" r="5" fill="blue"/>
</pattern>
</defs>
<circle cx="100" cy="100" r="100" fill="url(#pattern)"/>
</svg>
</svg>
注意:
Base svg
元素或其祖先元素不得 display:none
style或隐藏
属性,因为它们会破坏对基本 svg
的引用。所以我将容器 svg
元素的大小设置为0以隐藏屏幕。
Note:
Base svg
element or its ancestor elements must not have display:none
style or hidden
property, because they break reference to base svg
. So I set size of container svg
element to 0 to hide from screen.
这篇关于img src = svg在同一个文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!