js将链接生成二维码并转为图片的方法(图片可以

2024年07月21日 建站教程

HTML代码
<div class="QRcode-box">
    <div id="QRcode">
        <h3 id="qrcode" style="display: none;"></h3>
        <h3><img src="" id="qrcodeImg"></h3>
        <h4>微信长按识别二维码查看</h4>
        <h5>有效期至2020/09/26 11:00:00</h5>
    </div>
    <div class="share-type">
        <a href="javascript:shareWx()"><img src="images/share1.png">分享到微信</a>
        <a href="javascript:saveAlbum()"><img src="images/share2.png">保存到相册</a>
    </div>
</div>
//JS
//链接生成二维码
var qrcode = $('#qrcode').qrcode({
    width: 200,
    height: 200,
    text: "http://www.ipkd.com",
});
//二维码转图片
var canvas = qrcode.find('canvas').get(0);
var data = canvas.toDataURL('image/jpg');
$('#qrcodeImg').attr('src', data);
//保存到相册
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/8886/

展开阅读全文
相关内容