On the left is an rMQR Code. The other two views reveal its SVG contours. Drawing these outlines instead of separate squares or strips removes internal edges, prevents thin gaps when scaling or printing, and makes the SVG smaller.
Introduction
Hello, Qiita! I enjoy micro-optimizations. I like removing unnecessary work and finding a balance between what is needed and what is enough. This is more a mood than a rule. My barcode libraries began as tools for my own use.
Thank you for providing a place to share this work. This article introduces my rMQR implementation. It covers Kanji table compression and SVG contour tracing. I explain how both work and raise an open question about character mappings.
How I returned to these libraries
I happened to return to my GitHub profile after a long break. My Data Matrix library had collected stars and forks. People left thanks, reported a few encoding issues, and asked for new features. Someone even ported it to another language. A tool I made for myself was useful to others. Reading those messages made me want to work on it again. I could also see things to improve in code that once seemed complete.
I decided to fix the encoding issues. But the email account linked to the profile was already deleted. By chance, I returned just a few days before recovery would become impossible. I managed to restore it and get back to the libraries.
My QR library was published only as a minified file, and the source was lost. Reconstructing it brought back memories of writing the code. It also gave me fresh ideas. What began with a few fixes became a project I wanted to keep exploring.
Along the way, I remembered my plan to add Micro QR. This time, I chose rMQR instead. Data Matrix was already my usual choice for personal projects. I liked the long, narrow shape of rMQR and wanted to try it. That curiosity led to this library and, eventually, this article.
rMQR in JavaScript
Rectangular Micro QR Code is specified in ISO/IEC 23941:2022.1 My implementation supports all 32 symbol sizes and the M and H error-correction levels. It has no external dependencies and returns an SVG DOM element.
<div id="code"></div>
<script src="rmqr.min.js"></script>
<script>
document.getElementById('code')
.appendChild(rMQR('Hello, Qiita!'));
</script>
The default is to select the smallest fitting symbol by area. The generator combines Numeric, Alphanumeric, Byte, and Kanji segments, including the cost of switching modes. If H error correction fits the selected version, it uses the stronger level without enlarging the symbol.
Options allow an explicit size and error-correction level:
const svg = rMQR({
msg: 'Hello, Qiita!',
ver: 'R11x77',
ecl: 'H',
pal: ['#000', '#fff']
});
The interactive demo exposes the selected segments and the SVG contours. It is also a convenient way to compare inputs without writing code. Reading the result requires an rMQR-compatible reader.
The mode handlers live in a MODES array. When preparing a custom build, any handlers except Byte can be removed. Byte remains the required fallback. For example, removing Kanji and eliminating the now-unused table and decoder produces a smaller bundle; Japanese text then uses UTF-8 Byte segments. The repository already includes this variant as rmqr.light.min.js. Removing a mode can change the selected symbol size, since the remaining modes may need more bits.
Kanji: from Unicode to a compact lookup
I wanted Kanji support even though I rarely use it myself. A complete tool mattered to me. Once I learned that the implementation needed a large mapping table, the next question was how much I could compress it.
Why the arithmetic is only part of the job
Given a supported two-byte Shift JIS value, obtaining its 13-bit Kanji value is straightforward:
// Input: a valid two-byte Shift JIS value in the Kanji-mode ranges.
const offset = sjis >= 0xE040 ? 0xC140 : 0x8140;
const value = sjis - offset;
const index = (value >> 8) * 0xC0 + (value & 0xFF);
But the input to my library is a JavaScript string, represented as UTF-16. This formula starts after the Unicode-to-Shift-JIS mapping has already been done. Unicode and Shift JIS do not arrange these characters in an order that permits a simple arithmetic conversion.
The browser's TextEncoder only encodes UTF-8.2 Instead of including a general-purpose Shift JIS encoder, I store a table that lets the library look up the final Kanji value directly.
The packed data stores Unicode values in Kanji-index order. At runtime, the decoder reverses this mapping for direct lookup.
The reference table used here contains 8,192 positions, with 6,879 occupied entries and gaps marked as 0xFFFF. These counts describe this table, rather than establishing a separate repertoire limit for rMQR. The entries include hiragana, katakana, punctuation, and other symbols as well as kanji.
Store a short description of the table
Each position holds a 16-bit Unicode value. The uncompressed table therefore takes 16,384 bytes. Base64 makes those bytes convenient to embed in JavaScript, but increases the size to 21,848 ASCII characters.
The table is irregular overall, yet contains useful local patterns. My format describes it with a small set of commands:
| Command | Meaning |
|---|---|
A(value) |
Emit one explicit value. |
E(count) |
Skip unused positions. |
R(start, step, count) |
Emit an arithmetic series from an explicit start. |
P(step, count) |
Continue a series from the previous nonempty value. |
D(delta) |
Add a difference to the previous nonempty value. |
For example, a sequence of consecutive characters can be represented by its first value, a step of one, and its length. Irregular sections can use deltas or explicit values. ZigZag maps signed numbers near zero to small unsigned integers. Variable-length encoding then keeps those numbers short.
Signed 0 -1 +1 -2 +2 -3 +3
ZigZag 0 1 2 3 4 5 6
Delta tokens store the ZigZag value plus four. For example, D(+1) becomes 2 + 4 = 6, written as 06 in HEX. The offset reserves tokens 00–03 for the other commands. Series steps use ZigZag without this offset.
Here are positions 40–59 of the reference table, encoded as a standalone fragment. The Delta encoder uses an initial full value followed by individual differences. The Full encoder can also choose explicit values and series:
Delta encoder Full encoder
Value Command Bytes Command Bytes
---------++-------------------+------------------++-------------------+------------------
20 1D || A(201D) | 00 20 1D || A(201D) | 00 20 1D
FF 08 || D(-8469) | AD 84 01 || A(FF08) | 00 FF 08
FF 09 || D(+1) | 06 || D(+1) | 06
30 14 || D(+12555) | 9A C4 01 || A(3014) | 00 30 14
30 15 || D(+1) | 06 || D(+1) | 06
FF 3B || D(-12506) | B7 C3 01 || A(FF3B) | 00 FF 3B
FF 3D || D(+2) | 08 || D(+2) | 08
FF 5B || D(+30) | 40 || D(+30) | 40
FF 5D || D(+2) | 08 || D(+2) | 08
30 08 || D(+12459) | DA C2 01 || R(3008, +1, 10) | 02 30 08 02 0A
30 09 || D(+1) | 06 || ... |
30 0A || D(+1) | 06 || ... |
30 0B || D(+1) | 06 || ... |
30 0C || D(+1) | 06 || ... |
30 0D || D(+1) | 06 || ... |
30 0E || D(+1) | 06 || ... |
30 0F || D(+1) | 06 || ... |
30 10 || D(+1) | 06 || ... |
30 11 || D(+1) | 06 || ... |
FF 0B || D(-12550) | 8F C4 01 || A(FF0B) | 00 FF 0B
---------++-------------------+------------------++-------------------+------------------
40 bytes || Total: 32 bytes || Total: 25 bytes
Values and bytes are hexadecimal; steps, deltas, and counts are decimal. Each ... is a value generated by the preceding series, with no additional bytes stored. The series emits ten values, including its start. Signed differences wrap modulo 65,536. This fragment illustrates the commands; the complete-table measurements follow below.
A locally attractive command is not always the best choice for the complete table. A series has setup costs, and a shorter series can leave a better continuation. The encoder uses dynamic programming to choose the smallest binary command stream. At each position, it compares the cost of each valid command plus the best cost of the remaining suffix.
The complete-table results are:
| Representation | Binary stream | Base64 | Gzip of Base64 |
|---|---|---|---|
| Raw values | 16,384 bytes | 21,848 bytes | 14,033 bytes |
| Delta encoder | 10,784 bytes | 14,380 bytes | 10,094 bytes |
| Full encoder | 10,488 bytes | 13,984 bytes | 9,986 bytes |
Base64 sizes exclude quotes. Gzip uses level 9 on the standalone Base64 strings, excluding decoder code and wrappers. The encoder minimizes the binary stream, not gzip output. A complete bundle can give different compression results.
At runtime, rMQR decodes the table on first use and caches a sparse array indexed by Unicode value. A lookup returns the Kanji index or undefined when the character is unavailable.
Seven exclusions, and a question
Obtaining a lookup does not quite finish the job. Different Shift JIS mapping conventions can associate the same bytes with different Unicode characters. Unicode's historical mapping tables explicitly warn that product mappings can differ; its published Microsoft CP932 table provides a useful comparison.3
The current rMQR implementation removes these seven Unicode values from its Kanji lookup:
delete table[0x005C]; // REVERSE SOLIDUS
delete table[0x00A2]; // CENT SIGN
delete table[0x00A3]; // POUND SIGN
delete table[0x00AC]; // NOT SIGN
delete table[0x2016]; // DOUBLE VERTICAL LINE
delete table[0x2212]; // MINUS SIGN
delete table[0x301C]; // WAVE DASH
For example, the Shift JIS bytes 81 60 map to U+301C WAVE DASH in the historical mapping and U+FF5E FULLWIDTH TILDE in CP932. Similar-looking output can conceal a change in the decoded text.
These exclusions are a compatibility choice in my implementation. They do not mean that the characters are rejected. The optimizer sends them through UTF-8 Byte mode, using ECI 26 for non-ASCII text. Preserving that text on decoding requires a reader that honors the ECI assignment.
At present, keeping the exclusions in code makes this choice explicit. However, the table encoder can generate a variant with those positions already marked as unused. The runtime exclusions would then be unnecessary.
For readers familiar with these mappings: would you keep the seven exclusions visible in the library, or put them in the generated table? I would also appreciate practical experience with these distinctions in rMQR readers.
Building another table
The table tools include the source data, encoder, decoder, and a browser example. To encode a table, load the source array and encoder, then call:
const packed = encodeTable(KANJI_LOOKUP_TABLE);
The input stores Unicode values at their Kanji-index positions; 0xFFFF marks an unused position. Someone choosing a different mapping source or a smaller supported repertoire can generate a corresponding table without changing the compression algorithm. Retained entries must keep their correct positions. The supplied decoder expects 8,192 positions and unique nonempty values.
Unlike the sparse array used inside rMQR, this reusable decoder returns an Int16Array(65536) indexed by Unicode value. It contains a Kanji index or -1 for an unsupported character and occupies 128 KiB. Compressed source size and runtime memory are different measurements.
This is why I wanted to publish the tools alongside the packed data: the embedded table is one reproducible output, rather than the only possible one.
SVG: draw the boundary once
Before I worked with QR codes, I routinely used Illustrator's Pathfinder Unite to prepare vector artwork for print.
My older generator reduced SVG size by joining adjacent modules into horizontal strips. That was a practical solution I could implement in 2020. Later, while working on a gradient and transformations for an animation, thin white lines appeared between the pieces. The code looked like a picket fence.
I opened Illustrator again. This time I noticed the repetition. The generator already knew the whole matrix, yet I was asking another program to join its output. Why not generate the shape I wanted directly?
Keep only exposed sides
For each dark module, the algorithm checks its four neighbors. It retains a side only when that side borders a light module or the outside of the matrix. The shared side between two dark modules is omitted.
A solid block three modules wide and two high illustrates the difference. Six square subpaths can become one boundary:
<!-- Six adjacent squares -->
<path d="M0 0h1v1H0z M1 0h1v1H1z M2 0h1v1H2z
M0 1h1v1H0z M1 1h1v1H1z M2 1h1v1H2z"/>
<!-- The boundary of the same filled area -->
<path d="M0 0h3v2H0z"/>
Each retained edge has a direction, with the dark area on its right. Four bits at each grid vertex record its outgoing edges: 1 for right, 2 for down, 4 for left, and 8 for up.
On the left, the white point marks the start of an example walk. Dotted lines are shared internal sides; no edges are stored there. On the right, each direction is shown as a decimal value and a four-bit mask. Outgoing edges are stored at their starting vertex.
The bits can be combined. At a shared corner, outgoing right and left edges give 1 | 4 = 5 (0101 in binary).
The walk starts at a vertex with an unused outgoing edge. It selects the lowest set bit with mask & -mask, clears that bit, and pushes the next vertex onto a stack. Taking the right edge changes the example mask from 5 to 4. The left edge remains available.
0001 | 0100 = 0101
0101 ^ 0001 = 0100
When the current vertex has no outgoing edges left, the algorithm pops it from the stack and records the route in reverse. This joins branches into closed routes. Branch handling matters when dark modules meet at a corner. The walk can visit their shared vertex again to consume another edge.
Once a route is complete, the algorithm looks for another unused edge. It stops when all edges have been consumed.
When writing a route, the generator keeps its turns. Several unit steps in one direction become one h or v command, and z closes the final side.
Holes remain holes
An enclosed light area also has a boundary. Keeping dark modules on the right gives outer and inner boundaries opposite directions. Both belong to the same filled SVG path. Under the default nonzero fill rule, their winding contributions cancel inside the hole.4
The colored outlines in the opening illustration are a view of these routes. The normal output fills the contours; it does not stroke them.
What gets smaller
For the 27 × 13 rMQR Code in the opening illustration, with 192 dark modules, I compared four ways to write the foreground. These measurements cover only the uncompressed d attribute, without the illustration's translation or colors:
| Method | Subpaths | Characters in d
|
|---|---|---|
| One square per module | 192 | 2,682 |
| Vertical strips | 96 | 1,343 |
| Horizontal strips | 98 | 1,377 |
| Contours | 14 | 688 |
The 14 contour subpaths include holes. On this matrix, tracing saves about 74% compared with individual squares and 49% compared with the shorter strip representation. Other matrices give different results.
Path measurement details
All four methods use z for the closing side. The rectangle passes start at the bottom right and use absolute M commands followed by relative sides. The contour path uses relative moves and sides, as in the opening illustration. The counts exclude whitespace added for formatting.
The change also removes the internal boundaries responsible for the seams in my workflow.
In the demo, enable Explore SVG contours to inspect the routes. Setting vrb: 1 returns the per-module representation for comparison without changing the encoded matrix.
The contour generator is already used in my QR Code library. I also plan to add it to my existing Data Matrix library.
-
ISO/IEC 23941:2022, Rectangular Micro QR Code (rMQR) bar code symbology specification. ↩
-
WHATWG Encoding Standard, the browser encoding API.
TextEncodersupports UTF-8;TextDecoderalso supports legacy encodings. ↩ -
Unicode-hosted historical Shift JIS mapping and Microsoft CP932 mapping. The first is archived under
OBSOLETEand is used here to illustrate mapping differences, not as a current normative definition. ↩ -
SVG 2: the
fill-ruleproperty, including the defaultnonzerowinding rule. ↩