From 9a832a200d270c3f79e5220f69a2498d559ad010 Mon Sep 17 00:00:00 2001 From: Nayuki Minase Date: Fri, 22 Apr 2016 16:10:35 +0000 Subject: [PATCH] Added QrCode.drawCanvas() to JavaScript version of the library, by moving it from the demo program. --- javascript/qrcodegen-demo.js | 12 +----------- javascript/qrcodegen.js | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/javascript/qrcodegen-demo.js b/javascript/qrcodegen-demo.js index ee07226..e4fedf3 100644 --- a/javascript/qrcodegen-demo.js +++ b/javascript/qrcodegen-demo.js @@ -76,17 +76,7 @@ function redrawQrCode() { var scale = parseInt(document.getElementById("scale-input").value, 10); if (scale <= 0 || scale > 30) return; - // Draw QR Code onto canvas - var width = (qr.size + border * 2) * scale; - canvas.width = width; - canvas.height = width; - var ctx = canvas.getContext("2d"); - for (var y = -border; y < qr.size + border; y++) { - for (var x = -border; x < qr.size + border; x++) { - ctx.fillStyle = qr.getModule(x, y) == 1 ? "#000000" : "#FFFFFF"; - ctx.fillRect((x + border) * scale, (y + border) * scale, scale, scale); - } - } + qr.drawCanvas(scale, border, canvas); canvas.style.removeProperty("display"); } else { var code = qr.toSvgString(border); diff --git a/javascript/qrcodegen.js b/javascript/qrcodegen.js index 5a40e4e..10d46a6 100644 --- a/javascript/qrcodegen.js +++ b/javascript/qrcodegen.js @@ -37,6 +37,7 @@ * - Fields int version, size, mask * - Field QrCode.Ecc errorCorrectionLevel * - Method getModule(int x, int y) -> int + * - Method drawCanvas(int scale, int border, HTMLCanvasElement canvas) -> void * - Method toSvgString(int border) -> str * - Enum Ecc: * - Constants LOW, MEDIUM, QUARTILE, HIGH @@ -185,6 +186,24 @@ var qrcodegen = new function() { /*---- Public instance methods ----*/ + // Draws this QR Code symbol with the given module scale and number of modules onto the given HTML canvas element. + // The canvas will be resized to a width and height of (this.size + border * 2) * scale. The painted image will be purely + // black and white with no transparent regions. The scale must be a positive integer, and the border must be a non-negative integer. + this.drawCanvas = function(scale, border, canvas) { + if (scale <= 0 || border < 0) + throw "Value out of range"; + var width = (size + border * 2) * scale; + canvas.width = width; + canvas.height = width; + var ctx = canvas.getContext("2d"); + for (var y = -border; y < size + border; y++) { + for (var x = -border; x < size + border; x++) { + ctx.fillStyle = this.getModule(x, y) == 1 ? "#000000" : "#FFFFFF"; + ctx.fillRect((x + border) * scale, (y + border) * scale, scale, scale); + } + } + }; + // Based on the given number of border modules to add as padding, this returns a // string whose contents represents an SVG XML file that depicts this QR Code symbol. this.toSvgString = function(border) {