qr-code-styling-node 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,7 @@ npm install qr-code-styling-node
31
31
  <head>
32
32
  <meta charset="UTF-8">
33
33
  <title>QR Code Styling</title>
34
- <script type="text/javascript" src="https://unpkg.com/qr-code-styling-node@1.7.0/lib/qr-code-styling.js"></script>
34
+ <script type="text/javascript" src="https://unpkg.com/qr-code-styling-node@1.9.0/lib/qr-code-styling.js"></script>
35
35
  </head>
36
36
  <body>
37
37
  <div id="canvas"></div>
@@ -77,6 +77,98 @@ The package ships an ES module build (`import`), a CommonJS/UMD build (`require`
77
77
 
78
78
  ---
79
79
 
80
+ ### More styles, frames and labels
81
+
82
+ <img src="https://raw.githubusercontent.com/ducminhquan/qr-code-styling/master/src/assets/style_examples.png" width="720" />
83
+
84
+ New dot types `diamond`, `small-square`, `vertical-lines` and `horizontal-lines`, and a `rounded` type for both corner
85
+ options. A frame, a label and a plate behind the logo:
86
+
87
+ ```js
88
+ const qrCode = new QRCodeStyling({
89
+ data: "https://example.com",
90
+ dotsOptions: { type: "rounded", color: "#1d4ed8" },
91
+ cornersSquareOptions: { type: "rounded" },
92
+ frameOptions: { color: "#1d4ed8", radius: 24 },
93
+ labelOptions: { text: "SCAN ME" },
94
+ image: "https://example.com/logo.svg",
95
+ imageOptions: { backgroundColor: "#ffffff", backgroundRadius: 0.5 }
96
+ });
97
+ ```
98
+
99
+ The frame and label are drawn inside `width` x `height`; the code shrinks to fit.
100
+
101
+ `frameOptions` structure
102
+
103
+ Property|Type |Default Value |Description
104
+ --------|------|-------------------|--------------------------------------------
105
+ color |string|`'#000'` |Frame and label band color
106
+ width |number|4% of the size |Border thickness in px
107
+ radius |number|`0` |Outer corner radius in px
108
+ padding |number|4% of the size |Space between the frame and the code in px
109
+
110
+ `labelOptions` structure
111
+
112
+ Property |Type |Default Value |Description
113
+ ----------|---------------------------|------------------------------------|-----------------------------
114
+ text |string | |The text. Required
115
+ position |string (`'top' 'bottom'`) |`'bottom'` |Where the label goes
116
+ color |string |white on a frame, else the dots color|Text color
117
+ fontSize |number |7% of the size |In px
118
+ fontFamily|string |`'Helvetica, Arial, sans-serif'` |
119
+ fontWeight|string or number |`'bold'` |
120
+
121
+ ### QR art
122
+
123
+ <img src="https://raw.githubusercontent.com/ducminhquan/qr-code-styling/master/src/assets/art_examples.png" width="720" />
124
+
125
+ Blend a picture into the code with `art`. Two modes:
126
+
127
+ - `halftone` (default): the picture is redrawn as fine pixels, with each QR module kept in the middle. Use `colored: true` to keep the picture's colors.
128
+ - `colorize`: dots keep their shape (any `dotsOptions.type`) and are painted with a darkened copy of the picture, over a light copy of it.
129
+
130
+ ```js
131
+ const qrCode = new QRCodeStyling({
132
+ data: "https://example.com",
133
+ qrOptions: { errorCorrectionLevel: "H" }, // recommended for art
134
+ art: { image: "https://example.com/photo.jpg", mode: "halftone", colored: true },
135
+ imageOptions: { crossOrigin: "anonymous" } // the picture must be readable by a canvas
136
+ });
137
+ ```
138
+
139
+ QR art reads the picture's pixels, so it needs a canvas: it works as is in the browser, and on Node it needs
140
+ `nodeCanvas`. Pictures from another origin need CORS (`crossOrigin`), or the browser will block reading them.
141
+
142
+ `art` structure
143
+
144
+ Property |Type |Default Value|Description
145
+ ----------|----------------------------------|-------------|------------------------------------------------------------
146
+ image |string | |The picture (URL or data URL). Required
147
+ mode |string (`'halftone' 'colorize'`) |`'halftone'` |How the picture is blended in
148
+ colored |boolean |`false` |halftone: use the picture's colors instead of dots/background colors
149
+ background|boolean |`true` |colorize: show a light copy of the picture behind the dots
150
+ contrast |number (`0 - 1`) |`0.5` halftone, `0.7` colorize|Higher is easier to scan but shows less of the picture
151
+ crossOrigin|string | |Overrides `imageOptions.crossOrigin` for the picture
152
+
153
+ ### Checking that a code scans
154
+
155
+ `verify()` renders the code and decodes it with a QR decoder you pass in, so the library itself stays dependency-free.
156
+ It works with any decoder that has the [jsQR](https://www.npmjs.com/package/jsqr) signature.
157
+
158
+ ```js
159
+ import jsQR from "jsqr";
160
+
161
+ const result = await qrCode.verify({ decoder: jsQR });
162
+ // { readable: true, decoded: "https://example.com", attempts: 1 }
163
+
164
+ // For QR art: raise art.contrast step by step until the code scans, and keep that setting.
165
+ const tuned = await qrCode.verify({ decoder: jsQR, adjust: true });
166
+ // { readable: true, decoded: "...", contrast: 0.8, attempts: 3 }
167
+ ```
168
+
169
+ On Node, `verify()` needs `nodeCanvas` or `resvg` to draw the code. A decoder succeeding is a good sign, not a
170
+ guarantee: phone cameras are usually more forgiving than jsQR, but print size, light and screen glare matter too.
171
+
80
172
  ### API Documentation
81
173
 
82
174
  #### QRCodeStyling instance
@@ -105,6 +197,9 @@ backgroundOptions |object | |QR background st
105
197
  nodeCanvas |node-canvas | |Node only, optional. Needed for canvas output (png, jpeg, webp) on a server, see the Node section below
106
198
  jsdom |jsdom | |Node only, optional. Not needed for svg any more; still accepted for backward compatibility
107
199
  resvg |`Resvg` from `@resvg/resvg-js`| |Node only, optional. Produces png without node-canvas, see the Node section below
200
+ art |object | |Blend a picture into the code, see "QR art" above
201
+ frameOptions |object | |Border around the code, see "Frames and labels" above
202
+ labelOptions |object | |Text above or below the code, see "Frames and labels" above
108
203
 
109
204
  `options.qrOptions` structure
110
205
 
@@ -123,6 +218,8 @@ imageSize |number |`0.4` |Coeffic
123
218
  margin |number |`0` |Margin of the image in px
124
219
  crossOrigin |string(`'anonymous' 'use-credentials'`)| |Set "anonymous" if you want to download QR code from other origins.
125
220
  saveAsBlob |boolean |`false` |Saves image as base64 blob in svg type, see bellow
221
+ backgroundColor |string | |Draws a plate of this color behind the image
222
+ backgroundRadius |number (`0 - 0.5`) |`0.2` |Corner radius of the plate, relative to its size. `0.5` is round
126
223
 
127
224
  When QR type is svg, the image may not load in certain applications as it is saved as a url, and some svg applications will not render url images for security reasons. Setting `saveAsBlob` to true will instead save the image as a blob, allowing it to render correctly in more places, but will also increase the file size.
128
225
 
@@ -132,7 +229,7 @@ Property|Type
132
229
  --------|------------------------------------------------------------------------------|-------------|-------------------
133
230
  color |string |`'#000'` |Color of QR dots
134
231
  gradient|object | |Gradient of QR dots
135
- type |string (`'rounded' 'dots' 'classy' 'classy-rounded' 'square' 'extra-rounded'`)|`'square'` |Style of QR dots
232
+ type |string (`'rounded' 'dots' 'classy' 'classy-rounded' 'square' 'extra-rounded' 'diamond' 'small-square' 'vertical-lines' 'horizontal-lines'`)|`'square'` |Style of QR dots. With the last four, corners and alignment patterns stay solid unless you set a corner type
136
233
 
137
234
  `options.backgroundOptions` structure
138
235
 
@@ -147,7 +244,7 @@ Property|Type |Default Value|Description
147
244
  --------|-----------------------------------------|-------------|-----------------
148
245
  color |string | |Color of Corners Square
149
246
  gradient|object | |Gradient of Corners Square
150
- type |string (`'dot' 'square' 'extra-rounded'`)| |Style of Corners Square
247
+ type |string (`'dot' 'square' 'extra-rounded' 'rounded'`)| |Style of Corners Square
151
248
 
152
249
  `options.cornersDotOptions` structure
153
250
 
@@ -155,7 +252,7 @@ Property|Type |Default Value|Description
155
252
  --------|-------------------------|-------------|-----------------
156
253
  color |string | |Color of Corners Dot
157
254
  gradient|object | |Gradient of Corners Dot
158
- type |string (`'dot' 'square'`)| |Style of Corners Dot
255
+ type |string (`'dot' 'square' 'rounded'`)| |Style of Corners Dot
159
256
 
160
257
  Gradient structure
161
258
 
@@ -201,6 +298,13 @@ Param |Type |Default Value|Description
201
298
  ---------|------------------------------------|-------------|------------
202
299
  extension|string (`'png' 'jpeg' 'webp' 'svg'`)|`'png'` |Blob type on browser, Buffer type on Node
203
300
 
301
+ `QRCodeStyling.verify({ decoder, adjust }) => Promise<{ readable, decoded, contrast, attempts }>`
302
+
303
+ Param |Type |Description
304
+ -------|--------|--------------------------------------------------------------
305
+ decoder|function|A QR decoder with the jsQR signature `(rgba, width, height) => { data } \| null`
306
+ adjust |boolean |For QR art: raise `art.contrast` until the code scans. Default `false`
307
+
204
308
  `QRCodeStyling.update(options) => void`
205
309
 
206
310
  Param |Type |Description
@@ -0,0 +1,51 @@
1
+ /**
2
+ * QR art: blends a picture into the QR code while keeping it scannable.
3
+ *
4
+ * Both renderers (canvas and SVG) share this module. It reads the picture through a canvas
5
+ * (the browser's, or node-canvas on Node) and returns plain shapes and images to draw.
6
+ */
7
+ import { RequiredOptions } from "../core/QROptions";
8
+ import { ArtOptions, Canvas, FilterFunction, QRCode } from "../types";
9
+ type RGB = [number, number, number];
10
+ export interface ArtRect {
11
+ x: number;
12
+ y: number;
13
+ width: number;
14
+ height: number;
15
+ color: string;
16
+ }
17
+ export interface QRArea {
18
+ count: number;
19
+ dotSize: number;
20
+ x: number;
21
+ y: number;
22
+ }
23
+ export interface HalftoneArt {
24
+ mode: "halftone";
25
+ rects: ArtRect[];
26
+ }
27
+ export interface ColorizeArt {
28
+ mode: "colorize";
29
+ /** Full-size canvas holding a darkened copy of the picture inside the QR area, used to paint the dots. */
30
+ dots: Canvas;
31
+ /** Full-size canvas holding a light copy of the picture, drawn behind the dots (when art.background). */
32
+ background?: Canvas;
33
+ }
34
+ export type PreparedArt = HalftoneArt | ColorizeArt;
35
+ /** Default contrast per mode: colorize keeps the dot shapes, so it needs more contrast to scan reliably. */
36
+ export declare const DEFAULT_CONTRAST: {
37
+ halftone: number;
38
+ colorize: number;
39
+ };
40
+ export declare const getContrast: (art: ArtOptions) => number;
41
+ /** Luminance limits for "dark" and "light" pixels at a given contrast. */
42
+ export declare const getLimits: (contrast: number) => {
43
+ dark: number;
44
+ light: number;
45
+ };
46
+ export declare const toDark: (color: RGB, limit: number) => RGB;
47
+ export declare const toLight: (color: RGB, limit: number) => RGB;
48
+ export declare function createCanvas(options: RequiredOptions, width: number, height: number): Canvas;
49
+ export declare function getQRArea(options: RequiredOptions, count: number): QRArea;
50
+ export declare function prepareArt(options: RequiredOptions, qr: QRCode, filter: FilterFunction): Promise<PreparedArt>;
51
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Which modules of a QR symbol are function patterns (finders, timing, alignment, format and
3
+ * version information). QR art leaves these solid so scanners can still locate and read the code.
4
+ */
5
+ export type ModuleRole = "finder" | "function" | "alignment" | "data";
6
+ /** Returns a lookup of module roles for a symbol with `count` modules per side. */
7
+ export default function getModuleRoles(count: number): (row: number, col: number) => ModuleRole;
@@ -1,19 +1,24 @@
1
1
  import { RequiredOptions } from "./QROptions";
2
+ import { ArtRect } from "../art/art";
2
3
  import { QRCode, Gradient, FilterFunction, Canvas } from "../types";
3
4
  export default class QRCanvas {
4
5
  _canvas: Canvas;
5
6
  _options: RequiredOptions;
6
7
  _qr?: QRCode;
7
8
  _image?: HTMLImageElement;
9
+ /** Fill used for the dots instead of their color (QR art "colorize"). */
10
+ _dotsFill?: CanvasPattern;
8
11
  constructor(options: RequiredOptions);
9
12
  get context(): CanvasRenderingContext2D | null;
10
13
  get width(): number;
11
14
  get height(): number;
12
15
  getCanvas(): Canvas;
13
16
  clear(): void;
17
+ _drawFramed(qr: QRCode): Promise<void>;
14
18
  drawQR(qr: QRCode): Promise<void>;
15
19
  drawBackground(): void;
16
20
  drawDots(filter?: FilterFunction): void;
21
+ _drawArtRects(rects: ArtRect[]): void;
17
22
  drawCorners(filter?: FilterFunction): void;
18
23
  loadImage(): Promise<void>;
19
24
  drawImage({ width, height, count, dotSize }: {
@@ -1,7 +1,7 @@
1
1
  import QRCanvas from "./QRCanvas";
2
2
  import QRSVG from "./QRSVG";
3
3
  import { RequiredOptions } from "./QROptions";
4
- import { Extension, QRCode, Options, DownloadOptions } from "../types";
4
+ import { Extension, QRCode, Options, DownloadOptions, VerifyOptions, VerifyResult } from "../types";
5
5
  export default class QRCodeStyling {
6
6
  _options: RequiredOptions;
7
7
  _container?: HTMLElement;
@@ -29,6 +29,18 @@ export default class QRCodeStyling {
29
29
  */
30
30
  static _normalizeSVGForResvg(svgString: string): string;
31
31
  _rasterizeWithResvg(extension: Extension): Promise<Buffer | Uint8Array>;
32
+ /** Draws the current QR code to RGBA pixels, using a canvas or, failing that, resvg. */
33
+ _getPixels(): Promise<{
34
+ data: Uint8ClampedArray;
35
+ width: number;
36
+ height: number;
37
+ }>;
38
+ _decode(decoder: VerifyOptions["decoder"]): Promise<string | undefined>;
39
+ /**
40
+ * Checks that the QR code can be scanned by decoding the rendered picture.
41
+ * With `adjust: true` and QR art, raises art.contrast step by step until it scans.
42
+ */
43
+ verify({ decoder, adjust }: VerifyOptions): Promise<VerifyResult>;
32
44
  getRawData(extension?: Extension): Promise<Blob | Buffer | null>;
33
45
  download(downloadOptions?: Partial<DownloadOptions> | string): Promise<void>;
34
46
  }
@@ -16,6 +16,8 @@ export interface RequiredOptions extends Options {
16
16
  imageSize: number;
17
17
  crossOrigin?: string;
18
18
  margin: number;
19
+ backgroundColor?: string;
20
+ backgroundRadius?: number;
19
21
  };
20
22
  dotsOptions: {
21
23
  type: DotType;
@@ -1,4 +1,5 @@
1
1
  import { RequiredOptions } from "./QROptions";
2
+ import { ArtRect } from "../art/art";
2
3
  import { QRCode, FilterFunction, Gradient, Window, Canvas } from "../types";
3
4
  export default class QRSVG {
4
5
  _canvas?: Canvas;
@@ -14,15 +15,21 @@ export default class QRSVG {
14
15
  _imageUri?: string;
15
16
  /** True when no browser DOM or jsdom is available and the built-in virtual DOM is used. */
16
17
  _virtual: boolean;
17
- constructor(options: RequiredOptions);
18
+ /** Image used to paint the dots instead of their color (QR art "colorize"). */
19
+ _dotsImageHref?: string;
20
+ constructor(options: RequiredOptions, sharedWindow?: Window);
18
21
  get width(): number;
19
22
  get height(): number;
20
23
  getElement(): SVGElement;
21
24
  clear(): void;
25
+ _svgElement(name: string, attributes: Record<string, string | number>): SVGElement;
26
+ _drawFramed(qr: QRCode): Promise<void>;
22
27
  drawQR(qr: QRCode): Promise<void>;
23
28
  drawBackground(): void;
24
29
  drawDots(filter?: FilterFunction): void;
25
30
  drawCorners(): void;
31
+ _drawArtRects(rects: ArtRect[]): void;
32
+ _appendImage(href: string, x: number, y: number): void;
26
33
  imageToBlob(): void;
27
34
  _loadImageWithoutDom(): Promise<void>;
28
35
  loadImage(): Promise<void>;
@@ -32,7 +39,8 @@ export default class QRSVG {
32
39
  count: number;
33
40
  dotSize: number;
34
41
  }): void;
35
- _createColor({ options, color, additionalRotation, x, y, height, width, name }: {
42
+ _createColor({ options, color, additionalRotation, x, y, height, width, name, imageHref }: {
43
+ imageHref?: string;
36
44
  options?: Gradient;
37
45
  color?: string;
38
46
  additionalRotation: number;
@@ -1,3 +1,4 @@
1
+ import { Shape } from "../../shapes";
1
2
  import { DotType, GetNeighbor, RotateFigureArgsCanvas, BasicFigureDrawArgsCanvas, DrawArgsCanvas } from "../../../types";
2
3
  export default class QRDot {
3
4
  _context: CanvasRenderingContext2D;
@@ -7,6 +8,7 @@ export default class QRDot {
7
8
  type: DotType;
8
9
  });
9
10
  draw(x: number, y: number, size: number, getNeighbor: GetNeighbor): void;
11
+ _drawShape(shape: Shape): void;
10
12
  _rotateFigure({ x, y, size, context, rotation, draw }: RotateFigureArgsCanvas): void;
11
13
  _basicDot(args: BasicFigureDrawArgsCanvas): void;
12
14
  _basicSquare(args: BasicFigureDrawArgsCanvas): void;
@@ -1,3 +1,4 @@
1
+ import { Shape } from "../../shapes";
1
2
  import { DotType, GetNeighbor, DrawArgs, BasicFigureDrawArgs, RotateFigureArgs, Window } from "../../../types";
2
3
  export default class QRDot {
3
4
  _element?: SVGElement;
@@ -10,6 +11,7 @@ export default class QRDot {
10
11
  window: Window;
11
12
  });
12
13
  draw(x: number, y: number, size: number, getNeighbor: GetNeighbor): void;
14
+ _drawShape(shape: Shape): void;
13
15
  _rotateFigure({ x, y, size, rotation, draw }: RotateFigureArgs): void;
14
16
  _basicDot(args: BasicFigureDrawArgs): void;
15
17
  _basicSquare(args: BasicFigureDrawArgs): void;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Shapes shared by the canvas and SVG renderers. A shape is a list of path commands in absolute
3
+ * coordinates; `toCanvas` replays them on a 2D context and `toSVGPath` turns them into a path "d".
4
+ * Sub-paths of one module never overlap their neighbours, so the even-odd fill used by the
5
+ * renderers only cuts the holes that are meant to be holes (corner rings).
6
+ */
7
+ export type PathCommand = {
8
+ op: "M" | "L";
9
+ x: number;
10
+ y: number;
11
+ }
12
+ /** Circular arc around (cx, cy), angles in radians, clockwise on screen unless anticlockwise. */
13
+ | {
14
+ op: "A";
15
+ cx: number;
16
+ cy: number;
17
+ r: number;
18
+ start: number;
19
+ end: number;
20
+ anticlockwise?: boolean;
21
+ } | {
22
+ op: "Z";
23
+ };
24
+ export type Shape = PathCommand[];
25
+ export declare function toCanvas(context: CanvasRenderingContext2D, shape: Shape): void;
26
+ export declare function toSVGPath(shape: Shape): string;
27
+ export declare const diamond: (x: number, y: number, size: number) => Shape;
28
+ export declare const rect: (x: number, y: number, width: number, height: number) => Shape;
29
+ export declare const smallSquare: (x: number, y: number, size: number) => Shape;
30
+ /**
31
+ * A bar that joins its neighbours along one axis and gets a round cap where it has none.
32
+ * `before`/`after` are the neighbours above/below (vertical) or left/right (horizontal).
33
+ */
34
+ export declare const line: (x: number, y: number, size: number, vertical: boolean, before: boolean, after: boolean) => Shape;
35
+ /** Rounded rectangle, drawn clockwise. */
36
+ export declare const roundedRect: (x: number, y: number, width: number, height: number, radius: number) => Shape;
37
+ /** Finder ring with rounded corners: outer square minus inner square (even-odd). */
38
+ export declare const roundedRing: (x: number, y: number, size: number) => Shape;
39
+ export declare const roundedSquare: (x: number, y: number, size: number) => Shape;