The Code Behind Barcodes

4.3.8 Rendering the UPC

renderUPCA will render any barcode passed in as a string. This can be problematic. Everything will be fine if we validate the UPC and only call renderUPCA when the value is valid.

// Renders barcode to image
function renderUPCA(barcode){
  // Set cursor position
  cursor = [startPosition[0], startPosition[1]];

  // Fill the background
  fillBG();

  // Render start
  ctx.fillStyle = 'black';
  // Safe zone
  renderSpace(9);

  // Render start guard
  renderSequence(barcodes['startend'], true, false);

  // Iterate and render digits
  [...barcode].forEach(function(digitValue, digitIndex){
    // Is our digit on the left side?
    var isLeft = digitIndex > 5;

    // Render digit
    renderSequence(barcodes[digitValue], isLeft);

    // Render middle guard
    if (digitIndex == 5) {
      renderSequence(barcodes['mid'], false, false);
    }
  });

  // Render end guard
  renderSequence(barcodes['startend'], true, false);

  // Text numbers
  ctx.font = '30px sans-serif';
  ctx.textAlign = 'center';

  // Number system digit
  ctx.fillText(barcode[0], startPosition[0] + barSize[0] * 4.5, startPosition[1] + barMaxHeight + 15);

  // Left digits
  ctx.fillText(barcode.slice(1,6), startPosition[0] + barSize[0] * 35, startPosition[1] + barMaxHeight + 15);

  // Right digits
  ctx.fillText(barcode.slice(6,11), startPosition[0] + barSize[0] * 80, startPosition[1] + barMaxHeight + 15);

  // Check digit
  ctx.fillText(barcode[11], startPosition[0] + barSize[0] * 110, startPosition[1] + barMaxHeight + 15);
}

4.3.9 Putting It All Together

Time to write our last function! generateUPC is called when the “Generate” button is clicked or enter button is pressed on the keyboard. The function uses preprocessUPC to fetch and validate the user-input value and display any errors it encounters with the value. If all checks out, we will feed the barcode into renderUPCA. A usable UPC-A barcode will display below the form.

// Main function call for generating
function generateBarcode(){
  var barcode = preprocessUPC();
  if (barcode){
    renderUPCA(barcode);
  }
}