几天前我遇到了同样的问题。实际上,我需要转换包含图像的 svg:在这种情况下,我们必须手动导出 Base64 中的每个图像。但是,下面的代码段也应该适用于您的情况。我使用Raphael.Export库来获取 SVG。
var svgData = r.paper.toSVG(), //Obtaining the SVG element
parser = new DOMParser(),
//converting the svg in a DOM object
doc = parser.parseFromString(svgData, "text/xml");
//Getting all the images element in the SVG
var images = doc.querySelectorAll( "image" );
var canvas = document.createElement('canvas');
var ctx = canvas.getContext( "2d" );
var i, imgArr = new Array();
for(i=0; i<images.length; i++){
//for each image element, i need to obtain its Base64 representation
imgArr[i] = document.createElement("img");
imgArr[i].setAttribute( "src", images[i].href.baseVal);
imgArr[i].onload = function(i, images){
return function() {
ctx.drawImage( imgArr[i], 0, 0 );
// Replace the image href with its base64 representation
svgData = svgData.replace(images[i].href.baseVal,canvas.toDataURL( "image/png" ));
//if i'm converting the last element, create the img result
if(i==images.length-1){
var img = document.createElement('img'), canv = document.getElementById('myCanvas');
//generating the result svg image
img.setAttribute( "src", "data:image/svg+xml;base64," + btoa(svgData));
var context= canv.getContext( "2d" );
//when the img ready, we can obtain the png
img.onload = function() {
context.drawImage( img, 0, 0 );
var canvasdata = canv.toDataURL("image/png");
var pngimg = document.getElementById( "myImg" );
pngimg.setAttribute( "src", canvasdata);
//now pngimg contains the resulting image
};
}
}
}(i, images);
}
在您的 html 文档中,您需要一个带有 id="myImg" 的 img 标签
我希望它可以帮助:)