How It Works

Drawing Using SVG

An example of SVG code that draws one of these images is as follows:




1

  

This code draws the following image:

Setting the Features Dynamically

In this code, the height and width are pre-set to 48, the fill color to skyblue, the text to the number 1, and the text color black. Suppose we were able to set these values dynamically? We can do that using JavaScript. Suppose we have a function like this:

function draw_number_square (size, color, text, textcolor);
  

Then we might be able to use it like this...

draw_number_square (48, "skyblue", 1, "black");
draw_number_square (72, "darkred", 2, "white");
draw_number_square (36, "lightgreen", 3, "black");
draw_number_square (96, "blue", 4, "white");
  

...to draw images like this:

Drawing Using JavaScript

The JavaScript that implements this function looks like this:

function format_string (s, v)
{
  // sort of like printf
  //
  var rv = s;
  for (var i=0; i<v.length; i++) {
    rv = rv.replace ("%s", v[i]);
  }
  return rv;
}

function draw_number_square (size, color, text, textcolor) 
{
  // Generate the SVG code for this combination of box size, 
  //   background color, text, and textcolor
  //
  var strSVG = format_string (
    "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='%s' width='%s'>\n" + 
    "<rect x='10' y='10' height='%s' width='%s' stroke='black' stroke-width='1' fill='%s'>" +
    "</rect>" + 
    "<rect x='%s' y='0' height='10' width='10' fill='black'></rect>" + 
    "<text x='%s' y='%s' fill='%s' style='font-size:%spx;'>%s</text>" + 
    "</svg>",
    [size+24, size+24, size, size, color, (size+10)/2, 10+size/3, 10+(size*3/4), textcolor,
    size*2/3, text]);
  return strSVG;
}