Nadesłany przez Tomasz Lubiński, 19 lipca 2011 15:00
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.
ean8.js:
//EAN-8
//(c) 2010 by Tomasz Lubinski
//www.algorytm.org
var right = [
[1, 1, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 1, 1, 0],
[1, 1, 0, 1, 1, 0, 0],
[1, 0, 0, 0, 0, 1, 0],
[1, 0, 1, 1, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0],
[1, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 0],
[1, 0, 0, 1, 0, 0, 0],
[1, 1, 1, 0, 1, 0, 0]
];
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]
];
function convert(EAN8) {
/* inccorect length or check sum, return null */
if ((EAN8 == null) ||
(EAN8.length != 8) ||
(checkSum(EAN8) == false)) {
return null;
}
var bars = new Array(67);
for (i=0; i<67; i++) {
bars[i] = 0;
}
bars[0] = 1;
bars[1] = 0;
bars[2] = 1;
for (i=0; i<4; i++) {
for (j=0; j<7; j++) {
bars[i*7 + 3 + j] = left[EAN8[i]][j];
}
}
bars[31] = 0;
bars[32] = 1;
bars[33] = 0;
bars[34] = 1;
bars[35] = 0;
for (i=4; i<8; i++) {
for (j=0; j<7; j++) {
bars[(i-4)*7 + 36 + j] = right[EAN8[i]][j];
}
}
bars[64] = 1;
bars[65] = 0;
bars[66] = 1;
return bars;
}
/**
* calculates checksum of EAN13
*/
function checkSum(EAN8) {
var sum = 3 * EAN8[0] +
1 * EAN8[1] +
3 * EAN8[2] +
1 * EAN8[3] +
3 * EAN8[4] +
1 * EAN8[5] +
3 * EAN8[6];
sum %= 10;
sum = 10 - sum;
sum %= 10;
if (sum == EAN8[7]) {
return true;
}
else {
return false;
}
}
//initialize data
function generate(EAN8)
{
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(EAN8);
if (bars != null)
{
for (i=0; i<bars.length; i++) {
if ((i >= 0 && i<= 2) ||
(i >= 31 && i<= 35) ||
(i >= 64 && i<= 66)) {
length = 100;
} else {
length = 90;
}
if (bars[i] == 1) {
ctx.fillRect(i*2+20, 10, 2, length);
}
}
for (i=0; i<4; i++) {
ctx.fillText(EAN8[i], i*14+30, 105);
}
for (i=4; i<8; i++) {
ctx.fillText(EAN8[i], i*14+40, 105);
}
}
else
{
ctx.fillText("Nieprawidłowy numer", 50, 80);
ctx.fillText("Incorrect number", 50, 100);
}
}

