canvas截图并下载到本地功能实现

前端这点事 948 0

直接上功能代码,因为我也是网上找的。。。。

<html>

<body>
    <div style="display:block;margin:0 auto;width:638px;height:795px;">
        <div id="render">CONTENT</div>
    </div>

    <div id="template" style="margin:10px 0 0 385px;">
        <input type="button" onclick="qc0926()" value="下载图片" />
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.js"></script>

    <script type="text/javascript">
        var canvas, render, html, imgsrcgo;
        function renderHTMLAndSave() {
            var render = document.getElementById('render');
            html2canvas(render).then(function (canvas) {
                var imgsrc = canvas.toDataURL(); imgsrcgo = imgsrc;
            });
        }
        window.onload = renderHTMLAndSave();
        var imgsrc;
        var imgData;
        var type = 'png';
        var _fixType = function (type) {
            type = type.toLowerCase().replace(/jpg/i, 'jpeg');
            var r = type.match(/png|jpeg|bmp|gif/)[0];
            return 'image/' + r;
        };
        function saveFile(data, filename) {
            var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
            save_link.href = data;
            save_link.download = filename;
            var event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            save_link.dispatchEvent(event);
        };
        function qc0926() {
            imgData = imgsrcgo;
            imgData = imgData.replace(_fixType(type), 'image/octet-stream'); // 加工image data,替换mime type
            var filename = 'zgsjdomaincertification' + '_name' + '.' + type; // 下载后的文件名
            window.load = saveFile(imgData, filename); //下载域名证书
        };
    </script>
</body>

</html>


标签: canvas

发表评论 (已有0条评论)

还木有评论哦,快来抢沙发吧~