圖片實例:
簡介:
QRCode.js 是一個生成二維碼的JS庫。主要是通過獲取 DOM 的節點,再通過 HTML5 Canvas 繪制而成,不依賴任何庫。
用法:
1. 在項目中引入qrcode.min.js文件。 js文件網盤地址: https://pan.baidu.com/s/1kHB90FpMAJUvGvDNPpMm7Q 提取碼: hkz4
2. 創建ref節點:
<div style={{ width, height }} ref={qrcodeRef} />
3. 在render中創建ref 提供一個dom節點:
const qrcodeRef = React.createRef();
4. 定義創建二維碼的方法,以及調用:
function createdCode(id) { new QRCode(qrcodeRef.current, { text: `${url}?id=${id}`, // url or text width, // 二維碼寬度 height, // 二維碼高度 colorDark, // 二維碼顏色 colorLight, //二維碼背景底色 correctLevel: QRCode.CorrectLevel.H, //層級等級 }); }
其他方法:
const [qrc, setQrcode] = useState(''); //state中定義qrcode function creatCoe() { if(qrc) { qrc.makeCode('text'); // 重新生成二維碼 } else { const qrcode = new QRCode(qrcodeRef.current, { text, width, height, colorDark, colorLight, correctLevel: QRCode.CorrectLevel.H, }); setQrcode(qrcode); //在state中儲存 qrcode } } qrc.clear(); //清除代碼
這樣就會生成一個base64的img,如果要下載功能,去除當前節點的base64圖片的src即可!
QRCode.js ------------------------------------------------> GitHub地址