Nadesłany przez Tomasz Lubiński, 07 grudnia 2011 21:16
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.Pobierz pełne rozwiązanie.
Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
ean2.js:
//EAN-2
//(c) 2011 by Tomasz Lubinski
//www.algorytm.org
var left = [
[
[0, 0, 0, 1, 1, 0, 1],
[0, 0, 1, 1, 0, 0, 1],
[0, 0, 1, 0, 0, 1, 1],
[0, 1, 1, 1, 1, 0, 1],
[0, 1, 0, 0, 0, 1, 1],
[0, 1, 1, 0, 0, 0, 1],
[0, 1, 0, 1, 1, 1, 1],
[0, 1, 1, 1, 0, 1, 1],
[0, 1, 1, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1]
],
[
[0, 1, 0, 0, 1, 1, 1],
[0, 1, 1, 0, 0, 1, 1],
[0, 0, 1, 1, 0, 1, 1],
[0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 1, 1, 0, 1],
[0, 1, 1, 1, 0, 0 ,1],
[0, 0, 0, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 0 ,1],
[0, 0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 1, 1, 1]
]
];
var checksumTable = [
[0, 0],
[0, 1],
[1, 0],
[1, 1]
];
function convert(EAN2) {
/* inccorect length return null */
if ((EAN2 == null) ||
(EAN2.length != 2)) {
return null;
}
try {
var checkSum = EAN2[0]*10 + EAN2[1];
checkSum %= 4;
var bars = new Array(20);
for (i=0; i<20; i++) {
bars[i] = 0;
}
bars[0] = 1;
bars[1] = 0;
bars[2] = 1;
bars[3] = 1;
for (i=0; i<2; i++) {
for (j=0; j<7; j++) {
bars[i*9 + 4 + j] = left[checksumTable[checkSum][i]][EAN2[i]][j];
}
if (i<1) {
bars[i*9 + 11] = 0;
bars[i*9 + 12] = 1;
}
}
} catch(e) {
return null;
}
return bars;
}
//initialize data
function generate(EAN2)
{
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
/* clear canvas */
canvas.width = canvas.width;
/* prepare style */
ctx.fillStyle = "rgb(0,0,0)";
ctx.font = "10pt Arial";
ctx.textBaseline = "top";
ctx.textAlign = "left";
var bars = convert(EAN2);
if (bars != null)
{
for (i=0; i<bars.length; i++) {
if (bars[i] == 1) {
ctx.fillRect(i*2+20, 40, 2, 60);
}
}
for (i=0; i<2; i++) {
ctx.fillText(EAN2[i], i*17+30, 20);
}
}
else
{
ctx.fillText("Nieprawidłowy", 10, 10);
ctx.fillText("numer", 10, 25);
ctx.fillText("Incorrect", 10, 50);
ctx.fillText("number", 10, 65);
}
}

