Load src content to SVG image dynamically

后端 未结 2 1425
执念已碎
执念已碎 2020-12-14 23:23

I have a SVG rendered in the browser. I would like to change its content dynamically as attempted on http://jsfiddle.net/dt1510/pXA9P/1/ . In console.debug the

相关标签:
2条回答
  • 2020-12-14 23:53
    1. As you've seen, SVG <image> elements use an href attribute to source their content. Setting a src attribute (as with HTML's <img> elements) will not work.

    2. The href attribute is in the XLink namespace. Even though you never declared the namespace prefix, that's what it is, and so you need to set it as such.

    You can do this either via jQuery demo: http://jsfiddle.net/pXA9P/4/:

    $("image").attr('xlink:href',srcAirline);
    

    Or standard DOM demo: http://jsfiddle.net/pXA9P/5/:

    document.querySelector('image')
      .setAttributeNS('http://www.w3.org/1999/xlink','href',srcAirline);
    
    0 讨论(0)
  • 2020-12-14 23:59

    If you are using D3 library then you can use following to load svg image dynamically.

    d3.select("body") //select body in html
    .append("svg")  //add svg element in body tag
    .append("image")  // add image tag in svg element
    .attr('xlink:href',"image.svg") //set href property of image element..
    .attr("width",50) //set width of image
    .attr("height",50) //set height of image
    

    This can be very useful for those who are using D3 library.

    0 讨论(0)
提交回复
热议问题