Tutorial – Making a game in SVG


One of chrome’s best easter egg is the offline side scroller dino game. In this tutorial, I will be teaching you how to recreate a simplified version of it in SVG.

For this project, we will be using handlebars library to draw updates to the screen as it scrolls along.

note: the javascript in this tutorial is incomplete (i.e. each section only contains the relevant parts). To view the full code, visit the codepen.

Setting up the canvas

For a start, we will setup the code to render the SVG. We will only display the ground and the dino for now.

Every game will have a update loop to make the necessary movements and redraw the display. Our update loop will contain the code to render the game’s SVG figure.

This update loop is usually accompanied with a fps variable, indicating how long apart each update function call is.

// gid is shortcut for document.getElementById
var template = Handlebars.compile(gid('template').innerHTML);
var base = 280;
var fps = 20;

var data = {

function update(){
  gid('game').innerHTML = template(data);

The handlebars template for generating the game contains only the background, floor and the dino, as of now.

<svg viewBox="0 0 800 400">



  font-family: Helvetica, Arial, Sans-serif;
  font-size: 40px;


  <rect id="bg" x="0" y="0" width="800" height="400"></rect>
  <rect id="ground" x="0" y="380" width="800" height="20" fill="#FF0"></rect>
  <rect id="dino" x="80" y="{{dino_y}}" width="80" height="100"></rect>

Making the dino jump

Implementation To receive the clicks, we will have an overlay that will spread across the screen.

The jump function is really simple, there will be 3 main variables for this function, dino_y, dino_dy, and env_g.

The first variable, dino_y stores the current y coordinates of the player. dino_dy represents the vertical speed, positive for moving upwards, negative for moving downwards. env_g is gravity. Using these 3 variables, and some simple physics, we can make the dino jump.

Here, we will be making good use of the fps variable. Each variable change will be in terms of 1 seconds, so the fps will be used to add increments of the change during each update.

var data = {
  // ...

  /* main 3 variables for jumping calculation */

function jump(){
  /* only one jump at a time */
    data.dino_dy = data.dino_jump;
    data.dino_flr = false;

function update(){  
  /* change in speed and position */
  data.dino_dy -= data.env_g/fps;
  data.dino_y -= data.dino_dy/fps;

    data.dino_y = base;
    data.dino_flr = true;

  // ...

For each update loop, an increment of x/fps is added. After 1 second, the full value x will be eventually added.

Creating obstacles

In the game, there are all these different different obstacles that will be created on the fly. This part will show you a method of generating the obstacles.

There will be 3 classes of obstacles, small, medium and large, correponding to the different obstaclesin the original game, spike, small and large cactus.

For each set of obstacles (cactus or spikes), we will have a random distance between them (between 500px to 1200px).

Then depending on the type of obstacles, there will be different number of it in each set. There will always be 3 spkies, 2 to 3 small cactus, and 1 to 2 large cactus in our game.

Of course, we will have to animate the obstacles too. For that we will have the env_dx variable to set the speed of the obstacles, which will be used in the update loop to move the obstacles along.

var data = {
  // ...
  objs: []

function createObjs(){
  /* staring generating from x=80 */
  var last = 80;
  var objs = data.objs;

  /* get x position of the last obstacle */
    last = objs[objs.length-1]['x'];

  /* dunnid to generate until too far */
  if(last>1200){ return; }

    last += rand(5,12)*100;

    /* option of spike, small or large cactus */
    var opt = rand(2);
    var h = [50,100,150][opt];
    var w = [50,50,60][opt];

    /* random count of the obstacles in each set */
    var c = rand([3,1,1][opt],[4,3,2][opt]);
    for(var i=0; i<c; i++){

function update(){
  /* moving existing obstacles */
  for(x in data.objs){
    data.objs[x]['x'] -= data.env_dx/fps;
    if(data.objs[x]['x'] < -500){ delete data.objs[x]; }


In the update loop, the createObjs function is called to replenish the obstacles after the past spikes and cacti have long moved off the screen, thus creating an “infinite level”.

Setting the score

For the original dino game, the score is depedent on how long you survive in the game. We will thus have another timeout just to increment the score, 10 points per second of surviving.

function score(){
  data.env_s += 1;
  window.to_score = setTimeout(score,100);

Colliding with the dino

Since all the objects in the game are rectangles, we can use the simple boundary box collision test.

figure for collision test

The brief idea is that the x-axis segments of the 2 bounding boxes cannot collide, same goes to the corresponding y-axis segments.

function collide(obj){
  /* player's bounding box boundary */
  var dino = {
    y2:data.dino_y + 100

  /* object's bounding box boundary */
  var wall = {
    x2:obj.x + obj.w,
    y1:380 - obj.h

  /* simple rect obj collision */
  if(wall.x1<dino.x2 && wall.x2>dino.x1 && wall.y1<dino.y2 && wall.y2>dino.y1){
    return true;

  return false;

function update(){
  for(x in data.objs){
    if(!x){ continue;}

    /* only check if the obstacle is close enough */
        // we will handle this in more detail later

The collide function takes in the information of an obstacle, gets its extreme boundaries and compares it with the player’s extreme boundaries. If there is a collision, the function will return true.

Reseting the game

Time for some refactoring. To create a game that can be started and restarted over and over again, we will wrap all the initialization and the start of the update loop into a reset function.

Along with it, we should have a function to end the update loop, this will be aptly named lost. The will contain all the code for removing the timeouts and resetting the score.

function reset(){
  window.data = {


function lost(){
  /* can add other stuff if you want */

function update(){
  /* collision */
  for(x in data.objs){
    if(!x){ continue; }



Making it harder

There are a many improvements you can make to make the game more challenging. Here are some ideas:

  • Increase speed at higher scores
  • Increase gravity so player drop faster
  • Reduce distance between obstacles to reduce time for reaction
  • Increase the number of obstacles per set, making the obstacle set longer

As for the code, I will leave it out as an implementation exercise. Have fun!



Tutorial – SVG Rendering with Handlebars


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 id="marker" x="30" y="30">{{m}}</text>

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.