在JavaScript中创建SVG矢量图EAN13条码
Posted bywayboy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在JavaScript中创建SVG矢量图EAN13条码相关的知识,希望对你有一定的参考价值。
目标
EAN-13 商品条码由13位数字构成, 12位商品代码+1位校验码, 本次开发任务是在javascript中创建 EAN-13 商品条码, 生成矢量图, 方便后续根据用户需要使用画板生成不同尺寸的图片.
条码校验
最后一位校验码的值的计算方法如下:
- 取前面12位
- 校验值 = 求和(偶数位) * 3 + 求和(奇数位)
- 最终结果= 10 - (校验值 % 10)
SVG条码生成
实现代码:
function Ean13(code, conf)
const
A = [0x0D,0x19,0x13,0x3D,0x23,0x31,0x2F,0x3B,0x37,0x0B],
B = [0x27,0x33,0x1B,0x21,0x1D,0x39,0x05,0x11,0x09,0x17],
C = [0x72,0x66,0x6C,0x42,0x5C,0x4E,0x50,0x44,0x48,0x74],
num = code.split('').map(v=>parseInt(v)),
ver = [0x3F,0x34,0x32,0x31,0x2C,0x26,0x23,0x2A,0x29,0x25][num[0]];
let lines = [0,0,0,0,0,0,0,0,1,0,1];
for(var i=1;i<7;i++)
let k = (ver >> (6-i)) & 1 ? A[num[i]] : B[num[i]];
for(var j = 6; j >= 0; j --)
lines.push( (k >> j) & 1 ? 1 : 0);
lines.push(0,1,0,1,0)
for(var i=7;i<13;i++)
let k = C[num[i]];
for(var j = 6; j >= 0; j --)
lines.push( (k >> j) & 1 ? 1 : 0);
lines.push(1,0,1, 0,0,0,0,0,0,0,0);
var x=-1, w = 0, y = conf.name? (2+conf.fsize) : 0, nCount = lines.length, s = [],
bar = [`<svg viewBox="0 0 $nCount $conf.h" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">`];
lines.forEach((v,i)=>
if(0 == v)
if(w > 0)
var h = conf.h- y - 6.5;
if(x==8 || x == 10 || x == 54 || x == 56 || x == 100 || x == 102) h += 6.5;
s.push('M', x,' ', y,'h', w, 'v', h, 'h', -w, 'Z')
x = -1;w = 0;
else
if(-1 == x )x = i;
w++;
)
bar.push('<path d="', s.join(''),'"/>')
var tx = [2, 13,20, 27,34, 41,48, 59, 66,73,80,87,94],y = conf.h-0.4;
for(var i = 0; i < tx.length;i++)
let ch = num[i];
bar.push(`<text x="$tx[i]" y="$y" font-size="7" font-family="Verdana">$ch</text>`);
if(conf.name)
let y = conf.fsize - 0.5;
bar.push(`<text x="55.5" y="$y" font-size="$conf.fsize" width="111" text-anchor="middle" font-family="Verdana">$conf.name</text>`)
bar.push('</svg>')
return
svg:bar.join(''),
lines:lines.length
;
用法:
svgCode = Ean13('6928804014662',name:'香蕉你个芭拉',h:48,fsize:9)
效果如下:
以上是关于在JavaScript中创建SVG矢量图EAN13条码的主要内容,如果未能解决你的问题,请参考以下文章