基本思路:
- 1、获取svg所有元素;
- 2、如果有跨域图片,先把图片转成base64串再拿去渲染svg(解决跨域的关键点)
- 3、把svg转成svg格式的base64;
- 4、新建img元素,并将svg base64赋值给src;
- 5、onload的时候绘制到canvas画布内;
- 6、根据所需格式导出jpg或png图片base64串
svg:注意svg标签上一定要带着xmlns:xlink="http://www.w3.org/1999/xlink"属性,不然window.btoa生成的svgbase64串就已经不可用了
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0,0,238,200" id="svg" width="476" height="422">
<defs>
<pattern id="raduisImage" patternUnits="objectBoundingBox" width="32" height="32">
<image xlink:href="https://profile.csdnimg.cn/E/6/D/3_web_xiaolei" x="0" y="0" width="32" height="32" />
</pattern>
<linearGradient id="linearGradient" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:rgb(3,0,21);stop-opacity:1"/>
<stop offset="60%" style="stop-color:rgb(30,12,109);stop-opacity:1"/>
<stop offset="100%" style="stop-color:rgb(5,1,26);stop-opacity:1"/>
</linearGradient>
</defs>
<rect x="0" y="0" width="238" height="120" style="fill:url(#linearGradient)"/>
<rect width="226" height="96" x="5" y="14" style="fill:white;stroke-width:0;opacity:0.1;" />
<text x="16" y="35" style="font-size:11;fill:white;font-weight:600;">svg转 base64串 图片</text>
<line x1="12" y1="50" x2="225" y2="50" style="stroke:#AFABBF;stroke-width:1"/>
<circle cx="32" cy="76" r="16" fill="url(#raduisImage)"></circle>
<text x="53" y="70" style="font-size:10;fill:white;">web_xiaolei</text>
<text x="53" y="82" style="font-size:8;fill:white;">程序虐我千百遍,我待程序如初恋</text>
</svg>
svg效果:

转成jpg/png:
function loadSvg(){
var svg = document.getElementById('svg').outerHTML;
var img = document.createElement('img');
img.src = 'data:image/svg+xml;base64,'+window.btoa(unescape(encodeURIComponent(svg)));
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
console.log(canvas.toDataURL('image/jpeg'));
console.log(canvas.toDataURL('image/png'));
}
}
base64串显示效果

由于svg上含有跨域图片,图片没显示出来,所以最终处理结果:
function loadSvg(){
var img0 = document.createElement('img');
img0.crossOrigin = 'anonymous';
img0.src = 'https://profile.csdnimg.cn/E/6/D/3_web_xiaolei';
var canvas0 = document.createElement('canvas');
var ctx0 = canvas0.getContext('2d');
img0.onload = function(){
canvas0.width = 32*3;
canvas0.height = 32*3;
ctx0.drawImage(img0,0,0,32*3,32*3);
document.getElementById('svg-img').setAttribute('xlink:href',canvas0.toDataURL());
var svg = document.getElementById('svg').outerHTML;
console.log(svg)
var img = document.createElement('img');
img.src = 'data:image/svg+xml;base64,'+window.btoa(unescape(encodeURIComponent(svg)))
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
console.log(canvas.toDataURL('image/jpeg'));
console.log(canvas.toDataURL('image/png'));
}
}
}
解决跨域图片后的base64串显示结果:
