Skip to content

Instantly share code, notes, and snippets.

@jfdesrochers
Forked from jcormont/barcode-128-svg.js
Created July 9, 2018 04:09
Show Gist options
  • Save jfdesrochers/cdb900d24f0a5db87e0cd8f96f5c7d61 to your computer and use it in GitHub Desktop.
Save jfdesrochers/cdb900d24f0a5db87e0cd8f96f5c7d61 to your computer and use it in GitHub Desktop.
Simple Code-128 (128B) barcode SVG generator, in vanilla JS
var Barcode128Svg = (function () {
function Barcode128Svg(input) {
this.input = input;
this.factor = 2;
this.height = 75;
}
var lookup = {}, data = "212222222122222221121223121322131222122213122312132212221213221312231212112232122132122231113222123122123221223211221132221231213212223112312131311222321122321221312212322112322211212123212321232121111323131123131321112313132113132311211313231113231311112133112331132131113123113321133121313121211331231131213113213311213131311123311321331121312113312311332111314111221411431111111224111422121124121421141122141221112214112412122114122411142112142211241211221114413111241112134111111242121142121241114212124112124211411212421112421211212141214121412121111143111341131141114113114311411113411311113141114131311141411131".split(/(\d{6})/).filter(function (s) { return !!s });
for (var i = 32; i < 127; i++)
lookup[String.fromCharCode(i)] = [i - 32, data[i - 32]];
Barcode128Svg.prototype.toString = function () {
var h = this.height, f = this.factor;
var svg = "\n", x = 10 * f, sum = 104;
function draw(d) {
d.split("").forEach(function (n, i) {
svg += (i % 2) ? "\n" :
"<rect x=\"" + x + "\" y=\"0\" width=\"" + (+n * f) +
"\" height=\"" + h + "\" />";
x += +n * f;
});
}
draw("211214");
this.input.split("").forEach(function (c, i) {
var l = lookup[c] || [0, ""];
sum += l[0] * (i + 1);
draw(l[1]);
});
draw(data[sum % 103]);
draw("23311129");
return "<svg xmlns=\"http://www.w3.org/2000/svg\" " +
"xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" " +
"height=\"" + h + "px\" viewBox=\"0,0," + (x + f) + "," + h +
"\">" + svg + "</svg>";
};
Barcode128Svg.prototype.toDataUri = function () {
return "data:image/svg+xml;base64," + btoa(this.toString());
};
return Barcode128Svg;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment