给通过canvas生成的二维码添加logo

以jquery.qrcode为例来说,

生成二维码代码:

依赖jquery.js, jquery.qrcode.js

//计算宽,高,中心坐标,logo大小                                                                       
 var width = 256,height = 256;                                                                     
 var  x = width * 0.4,
    y = height * 0.4,
    lx = width * 0.2, 
    ly = height * 0.2; 
    $('#div')
        .qrcode({
            render : "canvas",
             width,                                                                     
            height: height,
            text: ‘this is content’
        })
        .hide();   
    var canvas = $("#div canvas")[0];
    //添加logo
    canvas.getContext('2d').drawImage($("#qrCodeIco")[0], x, y, lx, ly);
    //将canvas生成的二维码内容添加到img里,使得移动端能长按识别二维码
    $('#image').attr('src', canvas.toDataURL('image/png'));
<div id="div"></div>
<img id="qrCodeIco" src="logo.png" style="display:none;"/>
<img id="image"  src="" alt="code"/>
原文地址:https://www.cnblogs.com/ryans/p/8406096.html