The Code Behind Barcodes

4.2 Creating the Script

Now we will create a new JavaScript file named upc.js. At the top of the file, we will store all necessary variables. We will declare the size of the image (345x231px), a reference to the canvas, the size of each bar (module), and the height of the guard bars (start, middle, and end).

We will use a module width of 3px and a height of 160px. For the start, middle, and end guards, we want to extend the height by 20 pixels with a total height of 180px. This height difference is purely aesthetic.

// Image properties
const imageSize = [345, 231];
const img = document.getElementById('upcCanvas');
const ctx = img.getContext('2d');

// Bar values
const barSize = [3, 160]; // Size of standard bars
const barMaxHeight = 180; // Height of guard bars

Now, we will declare position data for the barcode. Then we will establish an offset for our rendering. startPosition is how far, in pixels, from the top-left, we will begin rendering the barcode. cursor is a moving point that tells the program where to render a barcode.

// Positioning data
var startPosition = [3,5];
var cursor = [0,0];

Next, we will store string constants used in our error prompt. We need one for when the user-entered UPC is incorrect. The other will display when the check digit is wrong.

// Error prompt values
const upcError = 'Please enter a valid 12-digit UPC.';
const checkError = 'The check digit is incorrect. Should be: ';

The program will use an array of values to render barcodes. The left and right digits do not matter here. The pattern is the same for both. We will toggle whether a space or a bar is rendered during rendering by checking the index against the halfway point (5).

// Barcode values
const barcodes = {
  'startend' : '111',
  'mid':'11111',
  0 : '3211',
  1 : '2221',
  2 : '2122',
  3 : '1411',
  4 : '1132',
  5 : '1231',
  6 : '1114',
  7 : '1312',
  8 : '1213',
  9 : '3112'
};