taro-code
Version:
Taro.js barcode & qrcode, Image & Canvas
64 lines • 2.8 kB
JavaScript
import Taro from '@tarojs/taro';
import { qrcode } from '../qrcode';
function autoIncreaseTypeNumber(text, options) {
var _a, _b, _c, _d, _e;
options = options !== null && options !== void 0 ? options : {};
const typeNumber = (_a = options.typeNumber) !== null && _a !== void 0 ? _a : 4;
const errorCorrectLevel = (_b = options.errorCorrectLevel) !== null && _b !== void 0 ? _b : 'M';
const size = (_c = options.size) !== null && _c !== void 0 ? _c : 500;
const black = (_d = options.black) !== null && _d !== void 0 ? _d : '#000000';
const white = (_e = options.white) !== null && _e !== void 0 ? _e : '#FFFFFF';
let qr;
try {
qr = qrcode(typeNumber, errorCorrectLevel !== null && errorCorrectLevel !== void 0 ? errorCorrectLevel : 'M');
qr.addData(text);
qr.make();
}
catch (e) {
if (typeNumber >= 40) {
throw new Error('Text too long to encode');
}
else {
return autoIncreaseTypeNumber(text, {
size: size,
errorCorrectLevel: errorCorrectLevel,
typeNumber: typeNumber + 1,
black,
white,
});
}
}
return qr;
}
export function drawCanvasQRCode(text, options) {
var _a, _b, _c;
const typeNumber = (_a = options.typeNumber) !== null && _a !== void 0 ? _a : 4;
const errorCorrectLevel = (_b = options.errorCorrectLevel) !== null && _b !== void 0 ? _b : 'M';
const size = (_c = options.size) !== null && _c !== void 0 ? _c : 500;
const qr = autoIncreaseTypeNumber(text, {
typeNumber,
errorCorrectLevel,
size,
black: options.foregroundColor,
white: options.backgroundColor,
});
const canvas = options.canvas;
const dpr = Taro.getSystemInfoSync().pixelRatio;
canvas.width = size * dpr;
canvas.height = size * dpr;
const width = canvas.width;
const ctx = canvas.getContext('2d');
ctx.fillStyle = options.backgroundColor;
ctx.fillRect(0, 0, width + options.padding * 2, width + options.padding * 2);
const tileW = (width - options.padding * 2) / qr.getModuleCount();
const tileH = (width - options.padding * 2) / qr.getModuleCount();
for (let row = 0; row < qr.getModuleCount(); row++) {
for (let col = 0; col < qr.getModuleCount(); col++) {
ctx.fillStyle = qr.isDark(row, col) ? options.foregroundColor : options.backgroundColor;
const w = Math.ceil((col + 1) * tileW) - Math.floor(col * tileW);
const h = Math.ceil((row + 1) * tileW) - Math.floor(row * tileW);
ctx.fillRect(Math.round(col * tileW) + options.padding, Math.round(row * tileH) + options.padding, w, h);
}
}
}
//# sourceMappingURL=qrcode.js.map