生成二维码及加入logo和文字

本文介绍了如何使用JavaScript和jQuery库在HTML页面中动态创建一个带有标题和Logo的二维码,展示了如何处理中文编码和调整图像布局的过程。
摘要由CSDN通过智能技术生成
<html>
<!-- 存放二维码的容器 -->
<div id='qrcode'></div>
<script type='text/javascript' src='http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js'></script> 
<script src="https://cdn.bootcss.com/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
<script type="text/javascript" >
//解决中文乱码问题
function toUtf8(str) {
    var out, i, len, c;
    out = "";
    len = str.length;
    for (i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i);
        } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
    }
    return out;
}
//二维码宽高
var qrcodewidth = 400;
var qrcodeheight = 400;
//canvas宽高
var canvaswidth = qrcodewidth;
var canvasheight = qrcodeheight + 100;
//logo宽高
var logowidth = 100;
var logoheight = 100;
//文字描述位置
var textleft = qrcodewidth / 2;
var texttop = qrcodeheight + 70;
//logo位置
var logoleft = (qrcodewidth - logowidth) / 2;
var logotop = (qrcodeheight - logoheight) / 2;

var qrcode = $('#qrcode').qrcode({
	render : 'canvas',
	text : toUtf8("https://blog.csdn.net/tswc_byy"),
	width : qrcodewidth,
	height : qrcodeheight,
	background : '#ffffff',
	foreground : '#000000',
});
var canvas = qrcode.find('canvas').get(0);
var img = new Image();
img.src = canvas.toDataURL('image/png');
img.onload = function() {
	canvas.width = canvaswidth;
	canvas.height = canvasheight;
	var ctx = canvas.getContext('2d');
	//设置画布背景
	ctx.fillStyle = '#ffffff';
	ctx.fillRect(0, 0, canvas.width, canvas.height);
	//设置文字样式
	ctx.fillStyle = '#000000';
	ctx.font = 'bold ' + 50 + 'px Arial';
	ctx.textAlign = 'center';
	//文字描述
	ctx.fillText("二维码标题", textleft, texttop);
	//绘制二维码
	ctx.drawImage(img, 0, 0);
	//设置logo
	var logo = new Image(logowidth, logoheight);
	logo.src = 'img/1.gif';    //Logo图
	logo.onload = function() {
		ctx.drawImage(logo, logoleft, logotop, logowidth, logoheight);
	}

}

</script>

最终生成效果图

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值