Skip to content

Instantly share code, notes, and snippets.

@johnnyb
Created May 12, 2022 21:00
Show Gist options
  • Select an option

  • Save johnnyb/8e4c888aa0ca5d4503b5e52391f4207a to your computer and use it in GitHub Desktop.

Select an option

Save johnnyb/8e4c888aa0ca5d4503b5e52391f4207a to your computer and use it in GitHub Desktop.
import * as ZXing from "html5-qrcode/third_party/zxing-js.umd"
export function performMonkeyPatches() {
console.log("Monkey patching")
// Monkey-patch based on https://github.com/zxing-js/library/pull/420/commits/7644e279df9fd2e754e044c25f450576d2878e45
const oldFunc = ZXing.HTMLCanvasElementLuminanceSource.toGrayscaleBuffer;
let inverterToggle = true;
ZXing.HTMLCanvasElementLuminanceSource.toGrayscaleBuffer = function(imagebuffer, width, height) {
const grayscaleBuffer = oldFunc(imagebuffer, width, height);
const len = grayscaleBuffer.length;
inverterToggle = !inverterToggle;
if(inverterToggle) {
for (let i = 0; i < len; i++) {
grayscaleBuffer[i] = 0xFF - grayscaleBuffer[i];
}
}
return grayscaleBuffer;
};
}
@AdamJrak
Copy link

AdamJrak commented Aug 29, 2022

Hey thanks for implementing a patch!

but quick question where do i call this performMonkeyPatches() function?

import {performMonkeyPatches} from './qrscanner-patch.js';

jQuery("document").ready(function(){
	const constraints = { facingMode: "environment"};
	const config = { fps: 29, qrbox: 250, videoConstraints: constraints };
	var html5QrcodeScanner = new Html5QrcodeScanner(
		"qr-reader", config);


	jQuery("#btnInitQRScan").on("click", startQRScan);
	function startQRScan()
	{
		jQuery("#btnInitQRScan").hide();
		
		performMonkeyPatches();
		html5QrcodeScanner.render(onScanSuccess,onScanFailure);

	}
});

but ZXing.HTMLCanvasElementLuminanceSource is undefined.

here is my qrscanner-patch.js

import * as ZXing from "./zxing-js.umd.js";

export function performMonkeyPatches() {
	console.log("Monkey patching")

	// Monkey-patch based on https://github.com/zxing-js/library/pull/420/commits/7644e279df9fd2e754e044c25f450576d2878e45
	console.log(ZXing);
	const oldFunc = ZXing.HTMLCanvasElementLuminanceSource.toGrayscaleBuffer;
	let inverterToggle = true;
	ZXing.HTMLCanvasElementLuminanceSource.toGrayscaleBuffer = function(imagebuffer, width, height) {
		const grayscaleBuffer = oldFunc(imagebuffer, width, height);
		const len = grayscaleBuffer.length;
		inverterToggle = !inverterToggle;
		if(inverterToggle) {
			for (let i = 0; i < len; i++) {
				grayscaleBuffer[i] = 0xFF - grayscaleBuffer[i];
			}
		}
		return grayscaleBuffer;
	};
}

@johnnyb
Copy link
Author

johnnyb commented Nov 23, 2022

I call it on application start.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment