sks-qrcode

适用于浏览和小程序的二维码库

Usage no npm install needed!

<script type="module">
  import sksQrcode from 'https://cdn.skypack.dev/sks-qrcode';
</script>

README

sks-qrcode

一个适用于web端,小程序上的二维码绘制库

npm install sks-qrcode --save

使用demo

在 h5 页面上使用。

import QRCode, {QRErrorCorrectLevel} from './qrcode';

function createQrcode(text, width, height) {
    var linkUrl = text;
    var qr = new QRCode(-1, QRErrorCorrectLevel.M);
    qr.addData(linkUrl);
    qr.make();
    qr.getModuleCount();

    var canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext('2d');

    var tileW = canvas.width / qr.getModuleCount();
    var tileH = canvas.height / qr.getModuleCount();

    // console.log(qr.getModuleCount());
    for(let row = 0; row < qr.getModuleCount(); row++) {
        for(let col = 0; col < qr.getModuleCount(); col++) {
            ctx.fillStyle = qr.isDark(row, col) ? "#000000" : "#ffffff";
            let w = (Math.ceil((col+1)*tileW) - Math.floor(col*tileW));
            let h = (Math.ceil((row+1)*tileH) - Math.floor(row*tileH));
            ctx.fillRect(Math.round(col*tileW),Math.round(row*tileH), w, h);
        }
    }

    return canvas;
}

在小程序里面使用。需要自己提供给一个 canvas 的实例

import QRCode, {QRErrorCorrectLevel} from './qrcode';

Page({
    onLoad: function (options) {
        const query = wx.createSelectorQuery();
        let _this = this;
        query.select('#id-canvas')
            .fields({node: true, size: true})
            .exec(function (res) {
                console.log(res);
                const canvas = res[0].node;
                instance = canvas
                // 绘制canvas
                _this.drawQrCode({
                    canvas: canvas,
                    data: {
                        qrCodeText: 'https://eng-static-dev71.sksedu.com/eng_wechat_adviser_qrcode.html?open_id=oRrx75SsMz1nDWv74dVzHpBGlOR8'
                    },
                });
            });
    },
    drawQrCode(options) {
        let canvas = options.canvas;
        const qrCodeText = options.qrCodeText
        const ctx = canvas.getContext('2d');

        let width = 200;
        let height = 200;
        var qr = new QRCode(-1, QRErrorCorrectLevel.L);
        qr.addData(qrCodeText);
        qr.make();
        qr.getModuleCount();
        var tileW = width / qr.getModuleCount();
        var tileH = height / qr.getModuleCount();
        for(let row = 0; row < qr.getModuleCount(); row++) {
            for(let col = 0; col < qr.getModuleCount(); col++) {
                ctx.fillStyle = qr.isDark(row, col) ? "#000000" : "#ffffff";
                let w = (Math.ceil((col+1)*tileW) - Math.floor(col*tileW));
                let h = (Math.ceil((row+1)*tileH) - Math.floor(row*tileH));
                ctx.fillRect(Math.round(col*tileW),Math.round(row*tileH), w, h);
            }
        }
    }
})