基本使用
插件安裝
cnpm install qrcodejs2 --save
// 或者
npm install qrcodejs2 --save
插件導入
使用commonjs或者es6模塊方式
import QRCode from 'qrcodejs2';
// 或者
let QRCode = require('qrcodejs2');
頁面容器
頁面增加一個容器標籤
<div id="qrcode" ref="qrcode"></div>
實例化
creatQrCode() {
let text = '二維碼內容';
let qrcode = new QRCode(this.$refs.qrcode, {
text: text, //二維碼內容字元串
width: 128, //圖像寬度
height: 128, //圖像高度
colorDark: '#000000', //二維碼前景色
colorLight: '#ffffff', //二維碼背景色
correctLevel: QRCode.CorrectLevel.H, //容錯級別
})
}
問題處理
1、清除已經生成的二維碼
方案一:this.$refs.qrcode.innerHTML = '';
方案二: qrcode.clear(); // 清除二維碼方法二
2、動態替換二維碼的內容
let string='新的內容'
qrcode.makeCode(string)
3、報錯提醒 Error: code length overflow ?
這是因為url太長,導致二維碼載入報錯,可以調低容錯率來處理。
修改參數:correctLevel: QRCode.CorrectLevel.H ,容錯級別,由低到高分別為L M Q H
4、字元串較長,二維碼顯示模糊怎麼辦?
可以嘗試先將生成的二維碼倍數擴大,然後在css上面固定顯示寬高,這樣可以擴大顯示像素精度
.qrcode-wrap{
width: 128px;
height: 128px;
}
.qrcode-wrap canvas,
.qrcode-wrap img {
width:100%;
height:100%;
}
<div id="qrcode" ref="qrcode" class="qrcode-wrap"></div>
creatQrCode() {
let text = '二維碼內容';
let qrcode = new QRCode(this.$refs.qrcode, {
text: text,
width: 128 * 3, //寬擴大3倍
height: 128 * 3, //高擴大3倍
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H,
})
}
5、二維碼想要帶白邊怎麼辦?
插件默認生成的圖片是沒有邊框的

如果只想在頁面顯示上有邊框
方案一:直接給容器上面加樣式,利用padding的特性,擠出白邊
.qrcode-border{
display: flex;
width: 128px;
height: 128px;
box-sizing: border-box;
padding: 10px;/*利用padding*/
border: 1px solid rgb(204, 204, 204);
}
<div id="qrcode" ref="qrcode" class="qrcode-border"></div>
方案二:給容器加一個帶邊框樣式的父級容器
.qrcode-container{
display: flex;
align-items: center;
justify-content: center;
width: 150px;
height: 150px;
border: 1px solid #cccccc;
}
<div class="qrcode-container">
<div id="qrcode" ref="qrcode"></div>
</div>
效果展示

✅PS:如果只想【列印】的白邊邊框,這兩種方案也可以

QRCode.js 文檔:
http://code.ciaoca.com/javascript/qrcode/
npm package 地址:
https://www.npmjs.com/package/qrcodejs2
github 地址:
https://github.com/davidshimjs/qrcodejs
如果想要頁面和下載的二維碼都帶白邊邊框
可以結合插件html2canvas來實現(如有其它方案,歡迎分享)
html2canvas 是一款利用javascript進行屏幕截圖的插件
//安裝
cnpm install --save html2canvas
//引入
import html2canvas from "html2canvas";
主要思路:
- 先使用QRCode生成二維碼圖片
- 然後使用html2canvas把帶樣式的二維碼生成新的圖片
- 隱藏QRCode生成的二維碼圖片
<div ref="canvas" class="canvas-box" :style="{display:(originImg===true?'none':'flex')}">
<div class="qrcode-box">
<div ref="qrcode" class="qrcode-img"></div>
</div>
<div class="qrcode-text">
掃一掃
</div>
</div>
<img :src="imgUrl">
最終效果

html2canvas 文檔地址:
http://html2canvas.hertzen.com/documentationgithub 地址:
https://github.com/niklasvh/html2canvas
前端插件JsBarcode生成條形碼
安裝和引入
//安裝
cnpm install jsbarcode --save
//引入
import JsBarcode from 'jsbarcode'
頁面容器
<template>
<!-- 條形碼容器,可選svg、canvas,或img標籤 -->
<svg id="barcode"></svg>
<!-- or -->
<canvas id="barcode"></canvas>
<!-- or -->
<img id="barcode"/>
</template
實例化
不要在DOM還未載入時,調用jsbarcode庫,比如create生命周期
簡版
JsBarcode('#barcode', 12345678,
{
displayValue: true // 是否在條形碼下方顯示文字
}
)
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/202537.html
微信掃一掃
支付寶掃一掃