svg转png图片

  • A+
所属分类:前端

修改代码后直接下载。

<html>
    <head>
        <style>
            * {
                background: transparent;
                margin: 0px;
                padding: 0px;
            }

            .main-warp {
                width: 1800px;
                height: 1500px;
            }

            .download {
                position: fixed;
                top:10px;
                width: 60px;
                height: 30px;
                line-height: 30px;
                right: 10%;
            }
        </style>

        <script>

            function converDownload() {
                var mainWarp = document.getElementById("main-warp");
                var svg = document.getElementById("orig-svg");

                var dd = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(mainWarp.innerHTML)));

                var img = new Image();
                img.src = dd;
                document.getElementById("help-div").appendChild(img);

                var canvas = document.createElement('canvas');
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0);
                setTimeout(function() {
                    var data = canvas.toDataURL('image/png');

                    var a = document.createElement('a');
                    a.href = data;  //将画布内的信息导出为png图片数据
                    a.download = "logo.png";  //设定下载名称
                    a.click(); //点击触发下载
                }, 1000);

            }
        </script>
    </head>
    <body>
        <button class="download" onclick="converDownload()">下载</button>
        <p id="main-warp" class="main-warp">
            <svg xmlns="http://www.w3.org/2000/svg"; viewBox="0 0 576 512"><path d="M528 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h480c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm0 400H48V80h480v352zM208 256c35.3 0 64-28.7 64-64s-28.7-64-64-64-64 28.7-64 64 28.7 64 64 64zm-89.6 128h179.2c12.4 0 22.4-8.6 22.4-19.2v-19.2c0-31.8-30.1-57.6-67.2-57.6-10.8 0-18.7 8-44.8 8-26.9 0-33.4-8-44.8-8-37.1 0-67.2 25.8-67.2 57.6v19.2c0 10.6 10 19.2 22.4 19.2zM360 320h112c4.4 0 8-3.6 8-8v-16c0-4.4-3.6-8-8-8H360c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8zm0-64h112c4.4 0 8-3.6 8-8v-16c0-4.4-3.6-8-8-8H360c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8zm0-64h112c4.4 0 8-3.6 8-8v-16c0-4.4-3.6-8-8-8H360c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8z"/></svg>
        <p>
        <div id="help-div" style="width: 100%;"></div>
    </body>
</html>
weinxin
独角兽驿站
公众号

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: