用qrcode生成二维码带logo 并下载图片(兼容IE10+)

jquery.qrcode.min.js 可以从这个地址下载https://www.jq22.com/yanshi294

image.png

html

image.png
$(function(){
        var qrcodewidth = 100;
        var qrcodeheight = 100;
        //canvas宽高
        var canvaswidth = qrcodewidth;
        var canvasheight = qrcodeheight + 40;
        //logo宽高
        var logowidth = 40;
        var logoheight = 40;
        //文字描述位置
        var textleft = qrcodewidth / 2;
        var texttop = qrcodeheight + 20;
        //logo位置
        var logoleft = (qrcodewidth - logowidth) / 2;
        var logotop = (qrcodeheight - logoheight) / 2;
        var qrcode = $('#qrcode').qrcode({
            render : 'canvas',
            text : utf16to8("{$data.user.invitation_url}"),
            width : qrcodewidth,
            height : qrcodeheight,
            background : '#ffffff',
            foreground : '#000000',
        });
        var canvas = $("#qrcode canvas")[0];
        var imgLogo = new Image(logowidth, logoheight);
        imgLogo.src = '__IMG__/logo_t.png';
        var context = canvas.getContext('2d');
        imgLogo.crossOrigin = 'Anonymous';
        imgLogo.onload = function(){
            context.drawImage(imgLogo ,logoleft, logotop, logowidth, logoheight);
            context.fillStyle = '#000000';
            context.font = 'bold ' + 16 + 'px serif';
            context.textAlign = 'center';
            //转成base64格式存下来 
            $('#saveQrCode').attr('href',$('#qrcode').find('canvas')[0].toDataURL("image/png"));
            $('#saveQrCode').attr('download', 'chart-download');
            console.log($('#qrcode').find('canvas')[0].toDataURL("image/png"));
        }
})

下载click事件

// 这里是获取到的图片base64编码,这里只是个例子哈,要自行编码图片替换这里才能测试看到效果
    var imgUrl = $(this).attr('href');
    // 如果浏览器支持msSaveOrOpenBlob方法(也就是使用IE浏览器的时候),那么调用该方法去下载图片
    if (window.navigator.msSaveOrOpenBlob) {
        var bstr = atob(imgUrl.split(',')[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        var blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
        } else {
        // 这里就按照chrome等新版浏览器来处理
        var a = document.createElement('a')
        a.href = imgUrl
        a.setAttribute('download', 'chart-download')
        a.click()
    }

你可能感兴趣的:(用qrcode生成二维码带logo 并下载图片(兼容IE10+))