如何使用canvas的toDataURL将svg图像的xlink:href标记中的图像转换为png / jpg图像。

时间:2017-12-06 05:31:34

标签: javascript snap.svg todataurl

SVG图像的xlink:href标签包含图像的路径,当我在浏览器中加载svg图像时,它会正确显示图像。

当我使用toDataURL转换svg图像时,转换后的jpg或png为空。

`
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)
`

我不知道xlink:href标签中的路径是否存在问题。

1 个答案:

答案 0 :(得分:0)

我能够通过使用toDataURL解析每个图像然后将其设置为href属性来解决这个问题:

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());