set img.src to dynamic svg element

前端 未结 2 689
一向
一向 2021-02-03 12:27

I know that I can set a svg file as the src of an HTML img element like this:


but can

2条回答
  •  鱼传尺愫
    2021-02-03 13:01

    You can do this with JavaScript:

    var svg = document.querySelector('svg'),
        img = document.querySelector('img');
    
    setImageToSVG(img,svg);
    
    function setImageToSVG(img,svg){
      var xml = (new XMLSerializer).serializeToString(svg);
      img.src = "data:image/svg+xml;charset=utf-8,"+xml;
    }​
    

    If your SVG element is dynamic (changing) then you would need to re-run this code each time the SVG element changed.

    Demo: http://jsfiddle.net/3PfcC/


    Alternatively, here's a demo showing @Robert's answer, using another element to reference the first, live:

    Demo: http://jsfiddle.net/3PfcC/3/

    
      
    
    
    
      
    
    

    The demo also shows that you can resize and otherwise transform the referenced SVG document, and that the reference is live: changes to the original are immediately reflected in the .

提交回复
热议问题