@nuintun/qrcode
Version:
A pure JavaScript QRCode encode and decode library.
99 lines (94 loc) • 2.47 kB
JavaScript
/**
* @module QRCode
* @package @nuintun/qrcode
* @license MIT
* @version 5.0.2
* @author nuintun <nuintun@qq.com>
* @description A pure JavaScript QRCode encode and decode library.
* @see https://github.com/nuintun/qrcode#readme
*/
;
const utils = require('../common/utils.cjs');
const GIFImage = require('../common/image/GIFImage.cjs');
/**
* @module Encoded
*/
class Encoded {
#mask;
#level;
#version;
#matrix;
constructor(matrix, version, level, mask) {
this.#mask = mask;
this.#level = level;
this.#matrix = matrix;
this.#version = version;
}
/**
* @property matrix
* @description Get the size of qrcode.
*/
get size() {
return this.#matrix.size;
}
/**
* @property mask
* @description Get the mask of qrcode.
*/
get mask() {
return this.#mask;
}
/**
* @property level
* @description Get the error correction level of qrcode.
*/
get level() {
return this.#level.name;
}
/**
* @property version
* @description Get the version of qrcode.
*/
get version() {
return this.#version.version;
}
/**
* @method get
* @description Get the bit value of the specified coordinate of qrcode.
*/
get(x, y) {
const { size } = this.#matrix;
if (x < 0 || y < 0 || x >= size || y >= size) {
throw new Error(`illegal coordinate: [${x}, ${y}]`);
}
return this.#matrix.get(x, y);
}
/**
* @method toDataURL
* @param moduleSize The size of one qrcode module
* @param options Set rest options of gif, like margin, foreground and background.
*/
toDataURL(moduleSize = 2, { margin = moduleSize * 4, ...colors } = {}) {
moduleSize = Math.max(1, moduleSize >> 0);
margin = Math.max(0, margin >> 0);
const matrix = this.#matrix;
const matrixSize = matrix.size;
const size = moduleSize * matrixSize + margin * 2;
const gif = new GIFImage.GIFImage(size, size, colors);
const max = size - margin;
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
if (x >= margin && x < max && y >= margin && y < max) {
const offsetX = utils.toInt32((x - margin) / moduleSize);
const offsetY = utils.toInt32((y - margin) / moduleSize);
gif.set(x, y, matrix.get(offsetX, offsetY));
} else {
// Margin pixels.
gif.set(x, y, 0);
}
}
}
return gif.toDataURL();
}
}
exports.Encoded = Encoded;