SwQrcodeGenerator
SwQrcodeGenerator encodes text as a QR code and renders it onto a <canvas>. Any prop change triggers an automatic re-render. Supports custom foreground / background colors, error correction levels, and quiet zone margins. Exposes download() and toDataURL() for both desktop downloads and mobile long-press saving.
Basic Usage
Pass a value to generate a QR code. The canvas re-renders automatically whenever value changes.
Basic usage
Custom Colors
Customize the QR code with foreground (dark modules, default #000000ff) and background (light modules, default #ffffffff). Colors use RRGGBBAA hex format (8 digits, including alpha).
Custom colors
Error Correction Level
Use errorCorrectionLevel to control fault tolerance: L (~7%), M (~15%, default), Q (~25%), H (~30%). Higher levels produce denser codes but remain scannable when partially obscured (e.g., with an overlaid logo).
Error correction level
margin + width combos
Download & Export
Call download() via a ref to trigger a browser download. On mobile browsers that don't support <a download>, download() rejects with MOBILE_LONG_PRESS — catch this and call toDataURL() instead, displaying the image so the user can long-press to save.
Download & export
Props
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
value | string | ✅ | — | Text to encode; any change triggers re-render |
width | number | ❌ | 200 | Canvas width in pixels (square output) |
foreground | string | ❌ | '#000000ff' | Dark module color, RRGGBBAA format |
background | string | ❌ | '#ffffffff' | Light module color, RRGGBBAA format |
errorCorrectionLevel | 'L' | 'M' | 'Q' | 'H' | ❌ | 'M' | Error correction level; use 'H' when overlaying a logo |
margin | number | ❌ | 4 | Quiet zone size in modules |
downloadFilename | string | ❌ | '' | Filename used by download(); falls back to qrcode-{timestamp}.png when empty |
Events
| Event | Payload | When |
|---|---|---|
ready | — | Canvas render completed |
error | { message: string } | QRCode.toCanvas threw an error |
Exposed Methods
| Method | Return | Description |
|---|---|---|
download() | Promise<void> | Triggers a PNG download; rejects Error('MOBILE_LONG_PRESS') on unsupported mobile browsers |
toDataURL() | string | null | Returns data:image/png;base64,...; use as <img :src> for mobile long-press saving |
Notes
- Color format:
foreground/backgroundare 8-digit hex strings (RRGGBBAA). The last two digits are alpha (ff= fully opaque). CSS color pickers typically return 6 digits — appendffmanually. - Reactive re-render: All props (
value,width,foreground,background,errorCorrectionLevel,margin) are watched. Changing any of them re-renders the canvas automatically. - Mobile download fallback: WeChat WebView and some Android WebViews don't support
<a download>. Catch theMOBILE_LONG_PRESSrejection and display thetoDataURL()image for the user to long-press save.