@nuintun/qrcode
Version:
A pure JavaScript QRCode encode and decode library.
70 lines (65 loc) • 1.81 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 Point = require('./Point.cjs');
const utils = require('./utils.cjs');
/**
* @module PlotLine
*/
// Mild variant of Bresenham's algorithm.
// see https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
class PlotLine {
#to;
#from;
#limit;
#steep;
#step;
#delta;
constructor(from, to) {
let toX = utils.toInt32(to.x);
let toY = utils.toInt32(to.y);
let fromX = utils.toInt32(from.x);
let fromY = utils.toInt32(from.y);
const steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
// Steep line.
if (steep) {
[fromX, fromY, toX, toY] = [fromY, fromX, toY, toX];
}
const stepX = fromX < toX ? 1 : -1;
this.#steep = steep;
this.#limit = toX + stepX;
this.#to = new Point.Point(toX, toY);
this.#from = new Point.Point(fromX, fromY);
this.#step = [stepX, fromY < toY ? 1 : -1];
this.#delta = [Math.abs(toX - fromX), Math.abs(toY - fromY)];
}
*points() {
const limit = this.#limit;
const steep = this.#steep;
const { y: toY } = this.#to;
const [stepX, stepY] = this.#step;
const [deltaX, deltaY] = this.#delta;
const { x: fromX, y: fromY } = this.#from;
let error = utils.toInt32(-deltaX / 2);
// Loop up until x === toX, but not beyond.
for (let x = fromX, y = fromY; x !== limit; x += stepX) {
yield [steep ? y : x, steep ? x : y];
error += deltaY;
if (error > 0) {
if (y === toY) {
break;
}
y += stepY;
error -= deltaX;
}
}
}
}
exports.PlotLine = PlotLine;