Skip to content Skip to sidebar Skip to footer

Img Src=svg In The Same Document

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 i

Solution 1:

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.

<spanclass="media-print-only"><divclass="svg-container"><svgwidth="200px"height="200px"><usexlink:href="#svgCanvas"/></svg></div></span><spanclass="media-no-print"><divclass="svgRealPlace"><svgwidth="200px"height="200px"><usexlink:href="#svgCanvas"/></svg></div></span><!--defining base SVG graphic--><svgwidth="0"height="0"><svgid="svgCanvas"width="200px"height="200px"><defs><patternid="pattern"width="10"height="10"patternUnits="userSpaceOnUse"><circlecx="5"cy="5"r="5"fill="blue"/></pattern></defs><circlecx="100"cy="100"r="100"fill="url(#pattern)"/></svg></svg>

Note: Base svg element or its ancestor elements must not havedisplay: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.

Solution 2:

I found a workaround to this problem - use jquery to move svg to printable place just before window.print() method and put the svg back to its original place straight after the method:

HTML

<spanclass="media-print-only">
  some-stuff
  <divclass="svg-container"></div></span><spanclass="media-no-print">
  some more stuff
  <divclass="svgRealPlace"><svgid="svgCanvas"><defs> some patterns </defs>
      some lines and rectangles that are using patterns in defs
    </svg></div>
  again more stuff
</span>

JS

functionprintButtonClicked(){
    $(".svg-container").append($('#svgCanvas'));
    window.print();
    $(".svgRealPlace").append($('#svgCanvas'));
}

Tested on Chrome, Firefox and Edge. I really hope there exists a better solution since DOM modifications are almost never a good idea.

Post a Comment for "Img Src=svg In The Same Document"