<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>svg 转图片,并设置 jpg 图片白色背景</title> <script src="https://ss.netnr.com/canvg@1.5.3/dist/browser/canvg.min.js"></script> </head> <body> <input type="button" class="btn-canvas" value="svg 转为 canvas" /> <input type="button" class="btn-image" value="canvas 存储图片" /> <select id="seimgtype"> <option>png</option> <option>jpeg</option> </select> <div id="container"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="130px" height="242px" viewBox="-0.5 -0.5 130 242"> <defs /> <g> <ellipse cx="65" cy="65" rx="49" ry="49" fill="#ffffff" stroke="#000000" stroke-width="2" pointer-events="none" /> <path d="M 27 70 C 27 84.91 44.01 97 65 97 C 85.99 97 103 84.91 103 70" fill="none" stroke="#000000" stroke-width="2" stroke-miterlimit="10" pointer-events="none" /> <path d="M 32 67 L 22 73" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none" /> <path d="M 98 67 L 108 73" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none" /> <ellipse cx="43" cy="51" rx="3" ry="8" fill="#ffffff" stroke="#000000" stroke-width="6" pointer-events="none" /> <ellipse cx="87" cy="51" rx="3" ry="8" fill="#ffffff" stroke="#000000" stroke-width="6" pointer-events="none" /> <image x="24.5" y="145.5" width="80" height="80" xlink:href="https://www.netnr.com/favicon.ico" pointer-events="none" /> </g> </svg> </div> <canvas id="canvasId"></canvas> </body> </html>
document.querySelector(".btn-canvas").addEventListener("click", function () { var ct = document.getElementById("container"); var svgnode = ct.children[0]; var cvs = document.getElementById("canvasId"); cvs.width = svgnode.clientWidth; cvs.height = svgnode.clientHeight; var gc = cvs.getContext("2d"); //填充白色背景 var ext = document.getElementById("seimgtype").value; if (ext == "jpeg") { gc.fillStyle = "#fff"; gc.fillRect(0, 0, cvs.width, cvs.height); } gc.drawSvg(ct.innerHTML.trim()); }); document.querySelector(".btn-image").addEventListener("click", function () { var ext = document.getElementById("seimgtype").value; var cvs = document.getElementById("canvasId"); var url = cvs.toDataURL("image/" + ext); var vimg = new Image(); vimg.src = url; document.body.appendChild(vimg); down(url, 'img.' + ext) }); function down(url, name) { var oA = document.createElement("a"); oA.download = name; oA.href = url; document.body.appendChild(oA); oA.click(); oA.remove(); }