QRCode.js
简介
这是一个原生的js库,用于生成二维码。
github地址:https://github.com/davidshimjs/qrcodejs
min.js地址:https://raw.githubusercontent.com/davidshimjs/qrcodejs/master/qrcode.min.js
到min.js地址下,直接赋值压缩包代码,放到自己本地js文件即可。需要用的时候直接引入使用。
使用示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>生成二维码示例</title>
<style>
#qrcode {
width: 120px;
height: 120px;
border: 1px solid pink;
}
</style>
</head>
<body>
<div id="qrcode">
<!--用于存放二维码的盒子,生成好的二维码会出现在这里-->
</div>
<!--引入本地库文件-->
<script src="./qrcode.min.js"></script>
<!--使用-->
<script>
var qrcode = new QRCode(document.getElementById("qrcode"), {
// 要生成二维码的网站链接 可以携带参数,例如:
// text: "https://guozia007.gitee.io/test-pages?userId=2333"
text: "https://guozia007.gitee.io/test-pages/",
// 存放二维码盒子的宽度,px
width: 120,
// 存放二维码盒子的高度,px
height: 120,
// 二维码颜色,黑白相间
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
</script>
</body>
</html>
网站页面https://guozia007.gitee.io/test-pages/
就被生成了一张如下的二维码:
用手机扫码,可查看到该网站页面(而且,在该页面可以获取到携带的参数):
jquery.qrcode.js
简介
很明显,这是一个jQuery的二维码生成库。体量很小,同样用法也很简单。
github地址:https://github.com/jeromeetienne/jquery-qrcode
min.js地址:https://raw.githubusercontent.com/jeromeetienne/jquery-qrcode/master/jquery.qrcode.min.js
到min.js地址下,直接赋值压缩包代码,放到自己本地js文件即可。需要用的时候直接引入使用。
使用示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>生成二维码示例</title>
<style>
#qrcode {
width: 120px;
height: 120px;
border: 1px solid pink;
}
</style>
</head>
<body>
<div id="qrcode">
<!--用于存放二维码的盒子,生成好的二维码会出现在这里-->
</div>
<!--因为要用到jquery,所以需要引入jquery库-->
<script src="./jquery 3.6.0.js"></script>
<!--引入本地库文件-->
<script src="./jquery.qrcode.min.js"></script>
<script>
$('#qrcode').qrcode({
// 要生成二维码的网站链接 可以携带参数,例如:
// text: "https://guozia007.gitee.io/test-pages?userId=2333"
text: "https://guozia007.gitee.io/test-pages/",
// 存放二维码盒子的宽度,px
width: 120,
// 存放二维码盒子的高度,px
height: 120
});
</script>
</body>
</html>
可以生成和原生库同样的二维码,手机扫码同样可以查看到网站页面。
调整二维码尺寸
当生成的二维码是显示在不同的设备上时,需要二维码随着设备尺寸做适当改变。
此时,应该给二维码加上尺寸。
根据二维码生成的机制, 会出现如下dom结构:
我们只需要在二维码容器内,给canvas标签一个样式即可:
canvas {
width: 100%;
}
意思是,让二维码最终的大小,把二维码容器撑满,和容器保持大小一致。