The Code Behind Barcodes

4.3.5 Rendering Spaces

Rendering a space is as easy as moving the cursor. The function expects the width in modules as input.

function renderSpace(width){
  cursor[0] += barSize[0] * width;
}

4.3.6 Rendering Bars

To render bars, we render a black rectangle at the cursor position with the specified dimensions. We will handle the width the same as in the previous function.

Since we are making guard bars taller, we have to detect whether the bar is for a digit or not. By default, we will assume the bar is for a digit.

function renderBar(width, isDigit=true){
  ctx.fillStyle = 'black';
  let height = barSize[1];

  // Set height to max for guard bars
  if (!isDigit)
    height = barMaxHeight;

  // Render bar
  ctx.fillRect(cursor[0], cursor[1], barSize[0] * width, height);

  // Shift cursor right
  cursor[0] += barSize[0] * width;
  }

4.3.7 Rendering Sequences

We could probably stop here, but there is one helper function that will make rendering barcodes a breeze. This function will accept a sequence of bar lengths, whether or not it is a left digit or a digit. In addition, the function will determine whether it is time to render a bar or space and the right bar or space to the screen.

function renderSequence(sequence, leftDigit=true, isDigit=true){
  // Are we going to render a bar or space first?
  var toggle = leftDigit;

  // Iterate the sequence and render appropriately
  [...sequence].forEach(function(sValue, sIndex){
    if (toggle)
      renderBar(sValue,isDigit);
    else
      renderSpace(sValue);

    toggle = !toggle;
  });
}