把页面转成图片下载到本地/手机相册(小编亲测有效)

2024年09月02日 建站教程

//把页面转成图片下载到本地/手机相册(小编亲测有效)

注:需要下载html2canvas.min.js、canvas2image.js

var QRcodeDownload = document.getElementById("QRcode");//需要转化下载的模块ID
//保存到相册/本地
function saveAlbum() {
    html2canvas(QRcodeDownload, {
        onrendered: function(canvas) {
            //添加属性
            canvas.setAttribute('id', 'thecanvas');
            //读取属性值
            // var value= canvas.getAttribute('id');
            document.getElementById('images').innerHTML = '';
            document.getElementById('images').appendChild(canvas);
            var oCanvas = document.getElementById("thecanvas");
            /*自动保存为png*/
            // 获取图片资源
            var img_data1 = Canvas2Image.saveAsPNG(oCanvas, true).getAttribute('src');
            saveFile(img_data1, '图片名称.png');
        }
    });
    // 保存文件函数
    var saveFile = function(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);
    };
}

本文链接:http://so.lmcjl.com/news/12095/

展开阅读全文
相关内容