as I change the symbol tag for an image in svg

1

I am studying web design and I have a question with svg, in my case I want to replace an icon that uses the path tag, for one that uses the image library to be able to insert an image. This is an example of a fragment of my code: I want to replace that with a png or jpg image, nothing more to limit, I say goodbye

    
asked by Francesco Vicentelli 28.03.2018 в 03:38
source

1 answer

0

First : A <symbol> tag within an SVG is never redirected. It's just a template you declare once and then you can reuse it with a <use> tag. From the MDN documentation :

  

Note that a symbol element itself is not   rendered. Only instances of a symbol element (i.e., a reference to a   symbol by a element) are rendered.

Second : You can use the canvg library to read the svg content and convert it to a canvas . And that canvas has the function toDataURL to generate a data-url that you will assign to a image in its src attribute.

The <svg> element that you need to convert must contain a <use> tag. You do not get anything with converting an element that only defines a <symbol>

function convertir() {

var the_svg=document.getElementById('el_svg').outerHTML.trim();
var canvas = document.createElement('canvas');
var container_img = document.getElementById('contenedor_img');
 
container_img.appendChild(canvas);

canvg(canvas, the_svg);
var la_img = document.createElement("img");

la_img.src = canvas.toDataURL("image/png", 1,{ignoreDimensions:false});
container_img.removeChild(canvas);

container_img.appendChild(la_img); 

}
#convertir {
  display:block;
  clear:both;
}
#contenedor_svg,
#contenedor_img {
padding:3px;
float:left;
display:inline-block;
width:170px;
height:150px;
border: 1px solid #ccc;
}
<script type="text/javascript" src="https://canvg.github.io/canvg/rgbcolor.js"></script> 
<script type="text/javascript" src="https://canvg.github.io/canvg/StackBlur.js"></script>
<script type="text/javascript" src="https://canvg.github.io/canvg/canvg.js"></script> 
  
<button id="convertir" onclick="convertir()">convertir en imagen</button>
<div id="contenedor_svg">
Yo contengo un svg
 
<svg id="el_svg" style="height:100px;width:100px">
  <symbol id="sym01">
    <path d="M98.5,47.5C96.5,45.5,81,35,62,35c-2.1,0-4.2,0.1-6.2,0.3L39,26c0,4.5,1.3,9,2.4,12.1C31.7,40.7,23.3,44,16,44L0,34
	c0,8,4,16,4,16s-4,8-4,16l16-10c7.3,0,15.7,3.3,25.4,5.9C40.3,65,39,69.5,39,74l16.8-9.3c2,0.2,4.1,0.3,6.2,0.3
	c19,0,34.5-10.5,36.5-12.5S100.5,49.5,98.5,47.5z M85.5,50c-1.4,0-2.5-1.1-2.5-2.5s1.1-2.5,2.5-2.5s2.5,1.1,2.5,2.5
	C88,48.9,86.9,50,85.5,50z"/>  
  </symbol>
<use href="#sym01"
     x="0" y="0" width="100" height="80"/>
</svg>
</div>
<div id="contenedor_img">
Yo contengo una imagen
</div>

From what I understand, canvg does not read the style sheet, so the SVG must have inline styles.

    
answered by 28.03.2018 в 13:12