SVG Element for SVG Cloning

Is it possible to โ€œuseโ€ a whole different svg in a separate svg? I want to use the map generated with d3 as an icon on the same page. This is what I tried, but it does not work.

<svg id="map"> svg stuff here </svg> <svg id="bar"> svg stuff here <use xlink:href="#map" height="20" width="30" ...> </svg> 

I also tried the cloning approach, but in the end all svg appeared in another svg and could not scale it. eg. makeicon ("# map", "#icon")

 function makeicon(source, destination) { //https://groups.google.com/forum/?fromgroups=#!topic/d3-js/-EEgqt29wmQ var src = d3.select(source); var dest = d3.select(destination); if (!src.empty() && !dest.empty()) { var newNode = d3.select(dest.node().insertBefore(src.node().cloneNode(true), src.node().nextSibling)) .attr("id", "newnode") .attr("width", null) // remove height and width of original svg .attr("height", null) .attr("viewBox", "0 0 20 30"); // try to make it smaller return newNode; 
+4
source share
3 answers

It should work fine.

Here is a simple example that works great in Firefox, Opera, and Chrome: http://jsfiddle.net/gew54/

A source:

 <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <style type='text/css'> svg { width: 100px; height: 100px; } </style> </head> <body> <svg id="map" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="20" fill="lime"/> </svg> <svg id="bar" viewBox="0 0 100 100"> <use xlink:href="#map" /> </svg> </body> </html> 
+3
source

Given the very limited support at the moment (only for Gecko engines), this can be done using the CSS 3 element() function.

MDN docs also point your case as a common use case:

... An especially useful scenario for using this would be an image in an HTML <canvas> element, then use this as a background.


Live demo

0
source

You can use svgWeb to make it work in webkit browsers.

0
source

Source: https://habr.com/ru/post/1445477/


All Articles