Skip to main content
CodingMarble

Code snippets

Generate QR Codes in JavaScript: Canvas, Download, Payloads

A QR code is just text encoded as a pattern of squares, so generating one in the browser means choosing the text, an error-correction level and a drawing target. Use a maintained open-source library to draw it to a canvas, format payloads like WiFi and UPI strings exactly, and test the result on real phones.

By CodingMarble · Published · 5 min read

Lines of code on a computer screen
Photo: Chris Ried on Unsplash

What a QR code actually encodes

A QR code stores a string of bytes. It does not know whether that string is a web address, a phone number or a payment request; the phone's scanner app inspects the text and decides what to do. If the text starts with https://, the camera app offers to open a link. If it starts with WIFI:, many phones offer to join a network. If it starts with upi://pay, payment apps can pick it up. Everything depends on the payload being formatted exactly as the receiving app expects.

The pattern you see is built from data modules arranged around three large finder squares in the corners, which let a scanner locate and orient the code. More text means more modules, which means a denser pattern with smaller squares. That has a practical consequence: the shorter the payload, the larger each square can be at a given print size, and the easier the code is to scan. A short link is almost always a better thing to encode than a long one with tracking parameters.

Error-correction levels and the size trade-off

QR codes include redundant data so a scanner can recover the message even if part of the code is dirty, scratched or covered. The standard defines four levels, named L, M, Q and H, which recover progressively more damage at the cost of more modules. L recovers the least and gives the smallest code for a given message. H recovers the most and gives the densest code.

  • L: smallest code, suited to clean screens where nothing will touch the code.
  • M: a balanced default for most web pages and printed flyers.
  • Q: a better choice for packaging or surfaces that may be scuffed.
  • H: the most redundancy, needed if you place a logo over the centre, but it makes the pattern denser.

Higher correction is not automatically better. Because it adds modules, a higher level at the same pixel size makes each module smaller, which can make the code harder to scan from a distance. Choose the lowest level that survives the conditions the code will face, and only use H when you are deliberately covering part of the code with a logo. Even then, keep the logo small and test it.

Drawing a QR code to a canvas with a library

Do not write the encoder yourself. The specification involves Reed-Solomon error correction, mask selection and version tables, and mistakes produce codes that look right but do not scan. Use a maintained open-source library instead. The example below uses the widely used npm package named qrcode. Library APIs change between releases, so treat this as an outline and check the package's current documentation for the exact option names and function signatures before shipping.

Shell· Install the library
npm install qrcode
JavaScript· Render text to a canvas (verify option names in the library docs)
import QRCode from "qrcode";

const canvas = document.querySelector("#qr");
const input = document.querySelector("#text");

export async function render(text) {
  if (!text.trim()) {
    const ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    return;
  }
  await QRCode.toCanvas(canvas, text, {
    errorCorrectionLevel: "M",
    margin: 4,
    width: 320,
    color: { dark: "#000000", light: "#ffffff" },
  });
}

input.addEventListener("input", () => render(input.value));
render("https://codingmarble.com");

The function clears the canvas for empty input, so users never see a stale code, and otherwise asks the library to draw. The margin option sets the blank border measured in modules, and 4 is the width the specification recommends. The width option sets the output size in pixels. If your payload is very long, the library may throw because it exceeds what a QR code can hold, so wrap the call in a try and show a message.

Downloading the code as a PNG

A canvas can export itself as a PNG data URL, and an anchor element with a download attribute turns that into a file. For printing, export a larger canvas than you display, because a 320 pixel image printed at business-card size will look soft. Rendering at a larger width keeps module edges crisp, and nothing stops you from showing it smaller on screen with CSS.

JavaScript· Export the canvas as a PNG file
export function downloadPng(canvas, filename = "qr-code.png") {
  const link = document.createElement("a");
  link.href = canvas.toDataURL("image/png");
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
}

document.querySelector("#download").addEventListener("click", () => {
  downloadPng(document.querySelector("#qr"));
});

If the canvas is empty or the text was invalid, you would still download a blank image, so disable the button until a code has been drawn. For vector output suitable for print shops, many libraries can also produce SVG strings; check the documentation for that option rather than converting a bitmap.

Formatting WiFi and UPI payloads correctly

Payload formats are strict text conventions, and a missing semicolon is enough to break them. The WiFi format is WIFI:T:WPA;S:network-name;P:password;; where T is the security type, S the network name and P the password. Special characters in the name or password, namely backslash, semicolon, comma, colon and double quote, must be escaped with a backslash. A UPI payment link uses the form upi://pay with query parameters: pa for the payee address, pn for the payee name, am for an optional amount, cu for the currency code and tn for a note. Values must be URL-encoded.

JavaScript· Build WiFi and UPI payload strings
function escapeWifi(value) {
  return value.replace(/([\\;,:"])/g, "\\$1");
}

export function wifiPayload({ ssid, password = "", security = "WPA", hidden = false }) {
  const parts = ["WIFI:T:" + security, "S:" + escapeWifi(ssid)];
  if (security !== "nopass") parts.push("P:" + escapeWifi(password));
  if (hidden) parts.push("H:true");
  return parts.join(";") + ";;";
}

export function upiPayload({ pa, pn, am, tn }) {
  const params = new URLSearchParams({ pa, pn, cu: "INR" });
  if (am) params.set("am", String(am));
  if (tn) params.set("tn", tn);
  return "upi://pay?" + params.toString();
}

console.log(wifiPayload({ ssid: "Cafe;Guest", password: "pa:ss" }));
// WIFI:T:WPA;S:Cafe\;Guest;P:pa\:ss;;
console.log(upiPayload({ pa: "shop@examplebank", pn: "Corner Shop", tn: "Order 42" }));
// upi://pay?pa=shop%40examplebank&pn=Corner+Shop&cu=INR&tn=Order+42

The output shows the escaping at work: the semicolon in the network name and the colon in the password each gain a backslash, and the at sign in the UPI address becomes %40. The UPI address in the example is made up, so replace it with the real payee address and confirm the current parameter rules with your payment provider or the official specification before putting a code on a counter. Never embed a real password in a code you will publish.

Contrast, quiet zone and testing with real phones

Scanners look for dark modules against a light background, and they depend on a blank border called the quiet zone, recommended at four modules wide. Cropping that border, placing the code against a busy photograph or letting a design element touch the edge are the most common reasons a code fails. Keep these rules in mind:

  • Use a dark foreground on a light background with strong contrast. Black on white is the safest.
  • Avoid inverted codes, light modules on a dark background. Some scanners handle them and some do not.
  • Keep the quiet zone clear on all four sides, including after you add a frame or a call-to-action label.
  • Do not stretch the code. Modules must stay square, so scale it uniformly.
  • Print large enough for the scanning distance. A code scanned from across a table needs bigger modules than one held in the hand.

Finally, test with real devices. Scan the code on screen and printed, using the default camera on at least one Android phone and one iPhone, in poor light, and from the distance a customer would actually use. Test the final printed artwork, not just the browser preview, because print scaling and ink spread change the result. If the code fails, try raising the size, shortening the payload or lowering the correction level before reaching for anything more complicated.

To compare your result with a finished version, CodingMarble runs a free QR code generator at qrcode.codingmarble.com.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.