From 4ffd42ac303e70f7edab61888e43ce64cd8186ce Mon Sep 17 00:00:00 2001 From: MultiMote Date: Wed, 11 Sep 2024 14:50:33 +0300 Subject: [PATCH] Improve barcode rendering (eliminate semi-transparent strips in solid lines) --- niimblue/src/fabric-object/barcode.class.ts | 37 +++++++++++++++++---- niimblue/src/utils/image_editor_utils.ts | 2 +- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/niimblue/src/fabric-object/barcode.class.ts b/niimblue/src/fabric-object/barcode.class.ts index db842cf..08649b3 100644 --- a/niimblue/src/fabric-object/barcode.class.ts +++ b/niimblue/src/fabric-object/barcode.class.ts @@ -75,7 +75,7 @@ export const Barcode = fabric.util.createClass(fabric.Object, { ctx.fillStyle = this.fill; const fontHeight = Math.round(Math.max(Math.min(this.height / 10, (this.width / this.text.length) * 1.5), 12)); - ctx.font = `bold ${fontHeight}px Courier New`; + ctx.font = `bold ${fontHeight}px Noto Sans Variable`; ctx.textBaseline = "top"; const fontWidth = ctx.measureText("0").width; const w2 = this.width / 2, @@ -94,12 +94,37 @@ export const Barcode = fabric.util.createClass(fabric.Object, { dh = this.height - fontHeight * 1.2; dw = (this.width - dp * 2) / this.bandcode.length; } + + let blackStartPosition = -1; + let blackCount = 0; + let long = false; + + // render barcode + // todo: snap barcode elements to the pixel grid (to make rendering sharp) for (let i = 0; i < this.bandcode.length; i++) { - const d = this.bandcode[i]; - if (d === "1") { - if (this.encoding === "EAN13" && EAN13_LONG_IDX.includes(i)) - ctx.fillRect(realX(dp + i * dw), realY(0), dw, dh + fontHeight * 0.7); - else ctx.fillRect(realX(dp + i * dw), realY(0), dw, dh); + const isBlack = this.bandcode[i] === "1"; + const xPos = realX(dp + i * dw); + + if (isBlack) { + blackCount++; + + if (blackStartPosition == -1) { + blackStartPosition = xPos; + } + + if (!long && this.encoding === "EAN13" && EAN13_LONG_IDX.includes(i)) { + long = true; + } + + if (blackStartPosition!= -1 && i === this.bandcode.length - 1) { + ctx.fillRect(blackStartPosition, realY(0), dw * blackCount, long ? dh + fontHeight * 0.7 : dh); + } + } else { + ctx.fillRect(blackStartPosition, realY(0), dw * blackCount, long ? dh + fontHeight * 0.7 : dh); + + blackStartPosition = -1; + blackCount = 0; + long = false; } } diff --git a/niimblue/src/utils/image_editor_utils.ts b/niimblue/src/utils/image_editor_utils.ts index 0f12482..ec9a624 100644 --- a/niimblue/src/utils/image_editor_utils.ts +++ b/niimblue/src/utils/image_editor_utils.ts @@ -140,7 +140,7 @@ export class ImageEditorUtils { public static addBarcode(canvas: fabric.Canvas): void { const barcode = new Barcode({ text: "1234567890128", - width: ImageEditorUtils.SIZE_DEFAULT * 2, + width: (canvas.width ?? ImageEditorUtils.SIZE_DEFAULT) - ImageEditorUtils.OBJECT_DEFAULTS.left, height: ImageEditorUtils.SIZE_DEFAULT, encoding: "EAN13", });