Measuring FPS with Canvas

This is actually a fairly simple one to do, though there is next to nothing on the web [at the moment] to show how it can be done, so since you’re here here you go. For the purpose of this article I’ll assume you already have canvas setup and a draw function of some kind. If you don’t, check this out, there is a sample of code at the bottom that has everything you’ll need to get started.

The first thing to do is setup some variables.

var drawInterval = 50;
var frameCount = 0;
var fps = 0;
var maxfps = 1 / (drawInterval / 1000);
var lastTime = new Date();

In the snippet above the first variable stores the draw interval, this needs to be used for the setInterval function that calls your draw function every n milliseconds.

// ...
setInterval(Draw, drawInterval);
// ...
// ...

The next two variables are easy enough. Frame count will hold a running count of how many frames we have drawn each second and FPS will store the current FPS the game is running at.

The third variable stores the maximum possible FPS the game can achieve at the current draw interval. This is basically the maximum number of times the draw function can be called within 1 second (1000 msec) under optimal conditions, for example in such cases were setInterval isn’t queuing due to high CPU usage in which case it will simple slow down. This slowdown possibility is why we need the final variable, last time, which will store the last time our FPS counter was updated.

So, onto calculating the FPS itself. At the top of your draw function that gets called by the setInterval function you will need the following.

var nowTime = new Date();
var diffTime = Math.ceil((nowTime.getTime() - lastTime.getTime()));
// ...
// ...

These two lines simply record the current time and find how long (in msec) it has been since the FPS counter was updated. If this is the first time the draw function is being run the initialization time we set above during declaration will be used. Immediately below these two lines add the following.

if (diffTime >= 1000) {
    fps = frameCount;
    frameCount = 0.0;
    lastTime = nowTime;
}

Here we first check if 1 second has passed since we last updated the FPS or not. If true, we set the FPS variable to the current frame count and then reset the frame counter itself so it can start counting for the next second. Before leaving set the last time variable to the current time to reset the time difference for the next draw loop.

Finally, at the end of your draw function you will need to increment the frame counter variable.

// ...
// ...
// ...
frameCount++;

And with that your done. Except you may want to see what FPS your game is running at. There are many ways to show this, you could, for example, simply update a HTML control on the page, set the document.title or even draw the value directly to the canvas screen like this.

ctx.save();
ctx.fillStyle = '#000000';
ctx.fillRect(0, height - 15, width, 15);
ctx.fillStyle = '#FFF';
ctx.font = 'bold 10px sans-serif';
ctx.fillText('FPS: ' + fps + '/' + maxfps, 4, height - 4);
ctx.restore();

This little snippet will draw a black bar at the bottom of your canvas window with white text showing the current FPS. You will need to make sure that the height and width variables are the values of your canvas elements height and width for it to work.

Putting it all together you should have something like this.

var ctx = null;
var width = 0, height = 0;
var drawInterval = 50;
var frameCount = 0;
var fps = 0;
var maxfps = 1 / (drawInterval / 1000);
var lastTime = new Date();

function init() {
    if (Setup('2d')) {
         setInterval(Draw, drawInterval);
    }
}

function Setup(method) {
    var canvas = document.getElementById('canvas');

    if (canvas && canvas.getContext) {
         width = canvas.width;
         height = canvas.height;

         ctx = canvas.getContext(method);
         return true;
    }

    return false;
}

function Draw() {
    var nowTime = new Date();
    var diffTime = Math.ceil((nowTime.getTime() - lastTime.getTime()));

    if (diffTime >= 1000) {
       fps = frameCount;
       frameCount = 0.0;
       lastTime = nowTime;
    }

    ctx.clearRect(0, 0, width, height);

    ctx.save();
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, height - 15, width, 15);
    ctx.fillStyle = '#FFF';
    ctx.font = 'bold 10px sans-serif';
    ctx.fillText('FPS: ' + fps + '/' + maxfps, 4, height - 4);
    ctx.restore();

    frameCount++;
}
Posted in Canvas, Javascript, Tutorial | 1 Comment

Building a Particle Engine with Canvas (Part 1)

So you want to create a fireworks show on your website or have a cool flame effect around a holiday photographs but you don’t have the time to create hundreds of looping pictures for an animation? Well, you don’t need to.

For Glacial Flame we set out to build a particle system to handle all our environment and spell effects. Personally, I didn’t know where to start with this one, my day job has me building large scale applications not making things look cool using specs of colour. But after getting the gist of what a particle engine is from our old friend Wikipedia I pretty much knew what we needed, just not how.

For those who don’t already know, a particle engine can be basically thought of as a swarm of images or shapes which follow a ‘fuzzy’ set of programmable instructions. For example, you could emit a hundred particles from an origin point on the screen and tell them that they should travel upwards and live for two hundred frames. Ordinarily this would simply create a blob of particles moving from the starting point upwards and then vanishing, pretty boring. The fuzziness or randomness comes into play by allowing you to emit the particles in such a way that some move slower than others, some start after a delay and maybe live longer than other and yet others may simply move a bit left or right. Now you’re boring straight line suddenly sounds more interesting.

Particle Fire 1

A very simple fire effect

So how? I started off by researching how other games do it, games written for DirectX or OpenGL, and soon found little gems like this one on NeHe’s site. Ignoring all the OpenGL specific code for drawing, this lesson does show quite well how to implement some of the particle behaviour underpinning the engine. Things such as gravity, fade, movement speed and lifespan.

With this I was able to start forming ideas on how to implement something in JavaScript / Canvas but first I needed to find a way to draw a particle. In NeHe’s article and many others like it particles are drawn from an image or texture. Canvas would probably struggle with this method. Firstly canvas isn’t yet able to draw hundreds of images to the screen quickly at the same time and secondly many of the manipulation techniques available in big libraries like OpenGL around images aren’t available to canvas just yet.

Particle Color 1

An early explosion of colour

In the end I settled on a simple rectangle using a radial gradient to create a smooth circle that could be any colour and size I chose.

function DrawParticle(x, y, radius, color1, color2) {
       var gradient = ctx.createRadialGradient(x, y, 0, x, y, radius / 2);
       gradient.addColorStop(0, color1);
       gradient.addColorStop(1, color2);

       ctx.fillStyle = gradient;
       ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
};

Give it a go. Try experiment by making a particle move across the screen changing colour as it goes. The below example should get you started, just copy it to a .html page and open it with your web browser.

<html>
<head>
     <title>Glacial Flame Particle Tutorial Part 1</title>
     <style type="text/css">
          body
          {
               background-color:#fff;
               color:#000;
               text-align: center;
               font-family: Verdana;
          }

          h2
          {
               font-size:10px;
               font-weight:normal;
          }

          #main
          {
               width:400;
               text-align:center;
               margin:0 auto;
          }        

     </style>
</head>
<body onload="init()">
     <div id="main">
          <h1>Tutorial Part 1</h1>
          <canvas id="canvas" width="300" height="200" style="border: 1px solid black; background-color: #fff;">
               Your browser does not support this content.
          </canvas>
          <h2>300 x 200</h2>
          <h2>Glacial Flame - <a href="mailto:dev@glacialflame.com">Iain Hamilton</a> & <a href="mailto:dev@glacialflame.com">Craig Wright</a></h2>
     </div>
     <script type="text/javascript">

          var ctx, canvasHeight, canvasWidth;

          // Particles current position within the canvas
          var px = 0, py = 100;

          // Starting colors (0 - 255 rgb)
          var r = 255, g = 255, b = 255;

          // Call this function to start everything off after the page loads
          function init() {
               SetupCanvas();

               if (ctx != null) {
                    // Run the draw function every 50 msec after canvas is setup
                    setInterval(Draw, 50);
               }
          };

          function SetupCanvas() {
               if (ctx == null) {
                    // Get the HTML canvas element
                    var canvas = document.getElementById('canvas');

                    if (canvas && canvas.getContext) {
                         // save the height and width for later use by javascript
                         canvasHeight = canvas.height;
                         canvasWidth = canvas.width;

                         // Start the particle in the middle of the screen for height
                         py = canvasHeight / 2;

                         // Get the canvas context, used to do all the drawing
                         ctx = canvas.getContext('2d');
                    }
               }

               ctx.globalCompositeOperation = 'lighter';
          };

          function Draw() {
               // Clear the canvas before every draw
               ctx.clearRect(0, 0, canvasWidth, canvasHeight);

               // Move the particle right 1 pixel every frame
               px++;

               // If the particle moves off the edge of the screen reset it
               if (px > canvasWidth) px = 0;

               // Every even number decrement the red intensity
               if (px % 2) r--;

               // Every third number decrement the green intensity
               if (px % 3) g--;

               // Decrement the blue intensity every frame
               b--;

               // Reset the color intensity when they hit 0
               if (r < 0) r = 255;
               if (g < 0) g = 255;
               if (b < 0) b = 255;

               // Draw the partcle itself
               DrawParticle(px, py, 40, "rgba(" + r + ", " + g + ", " + b + ", 1)", "rgba(0, 0, 0, 0)");
          };

          function DrawParticle(x, y, radius, color1, color2) {
               var gradient = ctx.createRadialGradient(x, y, 0, x, y, radius / 2);
               gradient.addColorStop(0, color1);
               gradient.addColorStop(1, color2);

               ctx.fillStyle = gradient;
               ctx.fillRect(x - radius, y - radius, radius * 2, radius * 2);
          };

     </script>
</body>
</html>

In the next tutorial I’ll discuss how you can add random fuzziness to particles to give you’re effects a more natural and fluid behaviour and introduce the emitter concept that we use to manage effects within Glacial Flame.

Posted in Canvas, Javascript, Particle System, Technology, Tutorial | 3 Comments

Canvas Tiles… And more Tiles

Glacial Flame is the name, isometric is the game. So many tile based classics have created game changing impacts, containing addictive crack like play that a list would be unorthodox. The term tile based doesn’t reflect the game style, instead the engine and method of game creation. Graciously used for memory restrictions on early consoles, formulating all time 1980s iconic arcade games, top down godly views and side scrolling platformers, both simulation development and strategy domination, fantasy worlds and 8 bit screens tile based games have rendered it all.

Computer games have come a long way in the last thirty years but the fundamentals for tile based engines have always been the same. Image repetition provided through tile sets or sprite sheets allow for reusable tiles that can be applied over and over from level to level. Instead of drawing out each level on a giant canvas (referred to as art based in the Flash world) each level is stored as a data structure that contains what tile images should be drawn and where. Evolving from a flat top-down perspective into isometric allowing for a greater sense of depth, tile games have remained popular through game advancement over the years.

Glacial Flame uses a tile based engine for creating the visual world. Although each tile starts its life in an array as a single integer it quickly develops into a fully visible and possibly attractive part of your game view.

Outdoor area consisting of 10,000 tiles.

Currently our tile engine allows for any size of map to be loaded and scrolled via placing your mouse to the sides of the game screen. Dynamically loaded from a database via PHP and relayed as XML, the world editor allows for saving and loading of different areas which can be of various sizes. As the map is scrolled the engine removes non-visible tiles and introduces those that are in view of the window port. Tiles and objects are correctly layered in the appropriate depths with any object being positional on top of any ground tile. While the prior map was an area consisting of 10,000 tiles the following screenshot shows that of a far smaller 3×3 map made of 9 tiles. Taking full advantage of the particle engine, tiles can have effects applied to them like the prior wall candles and the following candle stands.

Smaller 3x3 map made of 9 tiles

So how is a tile map drawn? In fact it can be rather simple in HTML5 Canvas. As stated in the previous post we will discuss how elements are achieved and put together various tutorials on creating your own. The following will presume you have a basic grasp of Canvas and are using an up to date browser which supports it. Having setup ctx as your canvas element and set body to call init() onLoad the following can be setup inside the init() function.

var map = Array([1,0,1,0,1], [1,1,1,0,1], [1,0,1,0,1]);

// Your map array as it sounds is basically your
// world and what will be drawn. Using a two
// dimensional Array we store the rows and columns
// To keep it simple we will use the Canvas fillRect
// call to only draw tiles represented by the number
// one.

for(var i=0;i<map.length;i++) {
    for(var j=0;j<map[i].length;j++) {
        // Now we loop through our map from start to end via
        // the length of dimensional array.
        if(map[i][j]) {
            ctx.fillStyle = '#FF0000';
            ctx.fillRect(j*20,i*20,20,20);
        }
    // Draw a rectangle at i + j position * 20 so that
    // our 20x20 pixel squares are correctly positioned.
    }
}

And that really is the basic minimum needed for creating a tile world. Next steps would be to replace the if statement with an array lookup using the value of the current tile to return an image or graphic.

As Glacial Flame progresses we will create more in depth tutorials aimed at various skill levels of programming, hopefully beginners and intermediates will find some of the content helpful.

Posted in Canvas, Javascript, Technology, Tile World | 2 Comments

Canvas, Particles and Fire

From the get-go we wanted Glacial Flame to be different. Not simply a technical demonstration of HTML5 but a game people would actually want to play and enjoy online. To achieve this we have set out to create a game that has all the bells and whistles people have come to expect with high quality animations, effects and character abilities all set atop a rich story and lore like all great role playing games (RPG).

Although the game is still in very early development we have already started to build components of the core engine and have a good idea of what we ultimately want to see at the other end of this journey. One of the first of these engine components we set out to create was the particle system.

In modern games particle engines are often used to create more fluid and dynamic effects than would be easily possible with pre scripted animations. Effects such as a burning candle or exploding magic bullet can be created using a few ‘particles’, a list of variables and a sprinkling of random, instead of hours and hours of labour behind Photoshop.

We wanted to start working on the particle system early on to test some of the limits of Canvas and see how far we would be able to exploit such a powerful tool to create the games effects. If it proved viable we’d be well on our way to achieving a more visually realistic game world and be able to apply more of our time into crafting a more complex game.

Example fire effect

Example fire effect

Although still evolving Canvas has proved to be perfectly capable of creating the effects we wanted to achieve and we have already started to create effects for all areas of the game, from dungeon torches to snow drifts and from simple magic bullets to large explosions. If you’re running this webpage in Google Chrome or Firefox you may have noticed an early stripped down version of the particle system in the footer of this site being used to create an animated snow blizzard.

Effect creator demo

Effect creator demo

As the game engine progresses we will start to post more details on how these engine components work, tutorials on how you can replicate many of the effects and how we overcame many of the challenges presented using such new and sometimes limiting technologies.

Posted in Canvas, Javascript, Particle System, Technology | 1 Comment

What is Glacial Flame?

Glacial Flame is a browser based role playing game (RPG) currently under development. The game is being designed to be complete, not just another quick flash-like game to pass the time but something you will want to come back to time and time again to catch up on the latest story, world events and find out what you’re friends achieved while you caught up on sleep.

Demo screenshot

Demo screenshot

The game will play much like the Diablo of old. From an isometric view you will control your own hero, issuing attacks, casting spells, summoning monsters or simply interacting with the environment and other players while growing ever more powerful and finding ever shinier loot.

Although the game will be multiplayer, allowing you to interact with other people in real time, it will also include an interesting and ever changing story with quests, live events and unexpected challenges that can be enjoyed solo or as part of a group.

The game is built on HTML 5 standards, meaning any browser that supports them such as Google Chrome or Firefox will be able to run it without the need for plug-ins like Adobe Flash from anywhere in the world at any time.

As development progresses you will be able to use this website to find out the latest development progress on the game, play early release demos and read up on the games back story and lore. We will also be posting tutorials on how the game works, the components it uses under the hood and how you can re-use them for your own websites, games or applications. So stay tuned!

Posted in About Glacial Flame | Leave a comment