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

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 .?

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 标签中的路径是否有问题。

我能够通过使用 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());