Search code examples
javascriptsnap.svgtodataurl

How to get the image in the xlink:href tag of an svg image to get converted to a png/jpg image using canvas's toDataURL .?


The SVG image's xlink:href tag contains a path to the image,when i load the svg image in the browser,it properly displays the image.

When i convert the svg image using toDataURL,the converted jpg or png is empty.

`
image.src = data:image/svg+xml;charset=utf-8,<svg%20xmlns="http:

//www.w3.org/2000/svg"%20width="871"%20height="435">  <foreignObject%20x="0"%20y="0"%20width="100%"%20height="100%"><div%20id="networkDiagramViewContainer"%20ng-right-click="show_traffic_events($event)"%20class="geDiagramContainer"%20style="cursor:%20default;%20width:%20251px;%20height:%20261px;%20overflow:%20initial;"%20xmlns="http://www.w3.org/1999/xhtml"><svg%20xmlns="http://www.w3.org/2000/svg"%20style="width:%20100%;%20height:%20100%;%20display:%20block;%20min-width:%20251px;%20min-height:%20261px;%20background-color:%20rgb(255,%20255,%20255);%20background-image:%20none;"><g><g/><g><g%20style="visibility:%20visible;"><image%20x="170"%20y="180"%20width="80"%20height="80"%20xlink:href="http://192.168.50.225:9002/media/apps/components/networkdiagram/stencils/clipart/others/Tire_128x128.png"%20xmlns:xlink="http://www.w3.org/1999/xlink"%20style="pointer-events:none"/><rect%20visibility="hidden"%20pointer-events="fill"%20x="170"%20y="180"%20width="80"%20height="80"/></g><g%20style="visibility:%20visible;"><image%20x="40"%20y="50"%20width="80"%20height="80"%20xlink:href="http://192.168.50.225:9002/media/apps/components/networkdiagram/stencils/clipart/others/Suit_Man_Blue_128x128.png"%20xmlns:xlink="http://www.w3.org/1999/xlink"%20style="pointer-events:none"/><rect%20visibility="hidden"%20pointer-events="fill"%20x="40"%20y="50"%20width="80"%20height="80"/></g></g><g/><g/></g></svg></div></foreignObject></svg>

var canvas = newCanvas(domNode);
canvas.getContext('2d').drawImage(image, 0, 0);
canvas.toDataURL('image/jpeg',1)
`

I dont know if the path in the xlink:href tag is an issue.


Solution

  • I was able to solve this by parsing each of the images using the toDataURL and then setting it to the href attribute :

    var img = new Image();
    var canvas = document.createElement('canvas');
    canvas.width = this.width;
    canvas.height = this.height;
    // draw the loaded image
    canvas.getContext('2d').drawImage(this, 0, 0);
    // set our <image>'s href attribute to the dataURL of our canvas
    image.setAttributeNS(xlinkNS, 'href', canvas.toDataURL());