Tutorial – SVG Rendering with Handlebars

Introduction

Handlebars is a javascript templating library that can be used to generate content on the fly. SVG (or scalable vector graphics) generates graphics from xml. In this tutorial, we are going to generate a figure (a SVG) to show the addition process of two two digit numbers.

SVG figure design

To align the numbers, we are going to split the numbers into their inidividual digits and then render them separately. Each digit will fit inside a 40 by 40 pixel square. And the “carry over marking” at the top, will fit inside a 20 by 20 pixel square.

The labelling of the numbers are as follows, the first row numbers start with a, so the tens place of the first number will be aa and the ones placing be ab. The tens place of the second number is ba and ones place bb. Similiar, hundreds, tens, and ones place of the answer will be ca, cb, and cc respectively.

<svg viewport='0 0 120 180' width='120' height='180'>
    <line x1="0" y1="110" x2="120" y2="110"></line>
    <text id="numbers">
        <tspan id="aa" x="50" y="60">{{aa}}</tspan>
        <tspan id="ab" x="90" y="60">{{ab}}</tspan>

        <tspan x="10" y="100">+</tspan>
        <tspan id="ba" x="50" y="100">{{ba}}</tspan>
        <tspan id="bb" x="90" y="100">{{bb}}</tspan>

        <tspan id="ca" x="10" y="160">{{ca}}</tspan>
        <tspan id="cb" x="50" y="160">{{cb}}</tspan>
        <tspan id="cc" x="90" y="160">{{cc}}</tspan>
    </text>
    <text id="marker" x="30" y="30">{{m}}</text>
</svg>

Generating the text for the diagram

There will be a form for us to get the two numbers, the first input will be id-ed a, the second input will be id-ed b. Then the button of course. The figure div will contain the final rendered SVG.

In the script, we first get the two numbers, add them up together, check whether the value will carry over. Then transform them to string, after that we will render the SVG.

function update(){
  /* shortcut functions */
  var $ = function(qry){
    return document.querySelector(qry);  
  };
  var _ = function(txt){
    return parseInt(txt);
  };

  /* getting the values */
  var a = $('#a').value;
  var b = $('#b').value;
  var c = (_(a) + _(b)).toString();

  /* transforming to text */
  var res = {};

  if(a.length>1){res.aa = a[0];}
  res.ab = a[a.length-1];

  if(b.length>1){res.ba = b[0];}
  res.bb = b[b.length-1];

  if(c.length>2){res.ca = c[0];}
  if(c.length>1){res.cb = c[c.length-2];}
  res.cc = c[c.length-1];

  /* the carry over marker */
  res.m = (_(res.ab)+_(res.bb)>9) ? '1' : '';

  return res;
}

After getting the values, we will render the SVG using handlebars library. And put the value into the #figure div.

var template = Handlebars.compile($('#template').innerHTML);
$('#figure').innerHTML = template(res);

Final product

When you put everything together, you have this. There you have it, handlebars rendering of a SVG figure.

Advertisements