原理:根据自己的掘金 url 连接,使用npm的qrcode模块生成二维码,其他人通过微信、支付宝、浏览器等 app 扫码进入到我们的掘金页面
以下命令是 Mac terminal 上运行,如果window 执行对应操作就行
# 创建一个项目文件夹
$ mkdir qrcode-demo
# 创建一个package.json用于存放 npm下载的模块
$ npm init -y
# 安装qrcode模块 就是使用这个模块生成二维码的
$ npm install --save qrcode
# 创建一个index.html tip: win powershell 运行: ni index.html
$ touch index.html
index.html 引入 qrcode
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>生成属于自己的二维码</title>
</head>
<style>
.qrcode-box {
width: 400px;
height: 400px;
}
</style>
<body>
<div id="qrcodeEl" class="qrcode-box"></div>
<!-- 引入qrcode -->
<script src="./node_modules/qrcode/build/qrcode.min.js"></script>
<script>
const qrcodeEl = document.querySelector('#qrcodeEl')
console.log('QRCode: ', QRCode)
</script>
</body>
</html>
复制qrcode 官网的代码 https://github.com/soldair/node-qrcode#tostringtext-options-cberror-string

<script>
const qrcodeEl = document.querySelector('#qrcodeEl')
const opts = {
errorCorrectionLevel: 'H',
type: 'image/jpeg',
quality: 0.3,
margin: 1,
color: {
dark: '#010599FF',
light: '#FFBF60FF'
}
}
QRCode.toDataURL('text', opts, function(err, url) {
if (err) throw err
const img = document.getElementById('image')
img.src = url
})
</script>
将ToDataURL改为 toString
text 改为当前的掘金url https://juejin.im/editor/drafts/5df1c639e51d4557fd76fd2b
扫码的时候就会访问这个url
color dark改为黑色#000
color light改为白色#fff
<script>
const qrcodeEl = document.querySelector('#qrcodeEl')
const opts = {
errorCorrectionLevel: 'H',
type: 'image/jpeg',
quality: 0.3,
margin: 1,
color: {
dark: '#000',
light: '#fff'
}
}
QRCode.toString(
'https://juejin.im/editor/drafts/5df1c639e51d4557fd76fd2b',
opts,
function(err, string) {
if (err) throw err
qrcodeEl.innerHTML = string
}
)
</script>
index.html完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>生成属于自己的二维码</title>
</head>
<style>
.qrcode-box {
width: 400px;
height: 400px;
}
</style>
<body>
<div id="qrcodeEl" class="qrcode-box"></div>
<!-- 引入qrcode -->
<script src="./node_modules/qrcode/build/qrcode.min.js"></script>
<script>
const qrcodeEl = document.querySelector('#qrcodeEl')
const opts = {
errorCorrectionLevel: 'H',
type: 'image/jpeg',
quality: 0.3,
margin: 1,
color: {
dark: '#000',
light: '#fff'
}
}
QRCode.toString(
'https://juejin.im/editor/drafts/5df1c639e51d4557fd76fd2b',
opts,
function(err, string) {
if (err) throw err
qrcodeEl.innerHTML = string
}
)
</script>
</body>
</html>
完