Illyriad: HTML5 WebGL Preview 2

We thought we’d up the game on the last demo and show a bit of lighting and animation.

A high level flour mill from Illyriad seemed an obvious choice!

Again this is purely HTML5 using the WebGL canvas and JavaScript; no plugins were used. We use mrdoob’s excellent Three.js library:

[youtube=https://www.youtube.com/watch?v=0bZmt3yQzmE]

We’ve included the full browser window in this recording to show that it is in fact running in a Chrome browser window. While it happily runs at 1080p, we’ve had to record at a much lower resolution as the screen capture utility slows everything down… Alas.

Illyriad: HTML5 WebGL Preview

We’ve done a bit of bloging about the “now”, but what about the future?

Well here at Illyriad we’ve been experimenting with WebGL and I can tell you we are impressed with how its shaping up.

Here’s a little taster of what we’ve been trying:

[youtube=https://www.youtube.com/watch?v=F22IvhUtrmM]

Its slightly shaky – but that’s my mouse movement not any lag from WebGL. Looks like I might never be a brain surgeon… haha

HTML5 Canvas: Creating a screenshot from multiple canvases in JavaScript

Programmatically creating screenshots from JavaScript of your canvas element is fairly straightforward; but how do you do it when your game or scene is composed of multiple overlaid canvases?

This example makes use of the canvas caching and it links into the animation loop for starting and stopping – your mileage may vary.

For simplicity, lets say we have 4 canvas elements in use, all of the same size (500×500) used in the following order:

  1. A far background: canvasFar
  2. A near background for a touch of Parallax scrolling: canvasNear
  3. A layer for player characters and other objects: canvasSprites
  4. A layer for special effects: canvasEffects

[code lang=”javascript”]
function TakeScreenshot() {
StopAnimating(); // Stop the animation loop

var bufferScreenshot = CreateCanvasCached("Screenshot");
bufferScreenshot.height = 500; bufferScreenshot.width = 500;
var contextScreenshot = bufferScreenshot.getContext("2d");
// Draw the layers in order
contextScreenshot.drawImage(
document.getElementById("canvasFar"), 0, 0, 500, 500);
contextScreenshot.drawImage(
document.getElementById("canvasNear"), 0, 0, 500, 500);
contextScreenshot.drawImage(
document.getElementById("canvasSprites"), 0, 0, 500, 500);
contextScreenshot.drawImage(
document.getElementById("canvasEffects"), 0, 0, 500, 500);

// Save to a data URL as a jpeg quality 9
var imgUrl = bufferScreenshot.toDataURL("image/jpeg", .9);

StartAnimating(); // Restart the animation loop
return imgUrl;
}
[/code]

Now calling TakeScreenshot() will return a data URL that contains the image – with this you can:

  • Set the src of an image element or css background
  • Open it in a new window to display it as an image (unfortunately you can’t set the content-disposition or filename of a data URL for automatic download)
  • Send it to your sever to base64 decode and create an image file which you can then to popup a download or embed in a page which can then be shared, tweeted, posted to Google+ or Facebook.
  • Use it as source image for more canvas fun or a WebGl texture

UPDATE: There is a toBlob() method on Canvas that allows the saving of generated files on the client-side which is coming in Chrome 14, hopefully other browsers will follow suit.

This should all work fine.  However if you are using images from different domains or a multiple sub-domains – either by using a CDN or for paralleling requests across domain names you will receive a:

SECURITY_ERR: DOM Exception 18

This is a security protection to ensure your code isn’t grabbing images it shouldn’t be, and sending them back to your server. I’ll post about how to work with this in a future post.

(Fix) Memory Leaks: Animating HTML5 Canvas

If you create canvas elements dynamically either for off-screen composition or sprite manipulation, when this is in an animation loop running hundreds of times a second it can start to leak memory.

I’m not entirely sure why this is; but it’s quite widespread in many browsers including Webkit. Perhaps the animation causes the browser to register as continually active which prevents the garbage collector from running – as it will clean it up if you stop the animation and change DOM elements e.g. from an Ajax update. But that’s just wild speculation…

What we are interested in is how to fix it, and also achieve some performance gains from not continuously creating DOM elements.

The trick is to create a function which caches these canvas elements and reuses them. The easiest way is to have a create canvas function that handles all this for you. To keep a handle on the different canvases in use in Illyriad, we use a named canvas element to ensure the correct one is returned. You can call them whatever is relevant:

[code lang=”javascript” title=”Create cached canvas”]
var CachedCanvases = new Object(); // Canvas element cache

function CreateCanvasCached(name) {
if (!CachedCanvases[name]) {
var canvas = document.createElement(‘canvas’);
CachedCanvases[name] = canvas;
return canvas;
}
return CachedCanvases[name];
};
[/code]

Using this is very simple, whenever you create a canvas dynamically that is just used for composition just (i.e. you won’t attach it to the DOM) use the cache function:

[code lang=”javascript”]
var SpriteCompositionCanvas = CreateCanvasCached("sprite");
SpriteCompositionCanvas.width = 64; SpriteCompositionCanvas.height = 64;
var SpriteCompositionContext = SpriteCompositionCanvas.getContext("2d");

[/code]

I’ll do another post on some of the wonderful composition operations you can do using canvas; when this technique will become very important.

If you are updating your page using Ajax and programmatically adding and removing the display of canvas elements you will want to clear the canvas cache when you change page by adding a cache clean up to your ajax page unload function.

[code lang=”javascript”]
function CleanupCachedCanvasses() {
var delList = new Array();
for (name in CachedCanvases) {
delList.push(name);
}
for (i = 0; i < delList.length; i++) {
delete CachedCanvases[delList[i]];
}
delete delList;
}
[/code]

Now you should be good to go!

HTML5 Canvas: Animation Loop – Only work when you have to

Animating HTML5 Canvas be it 2d or WebGl can put a strain on the end user’s browser.

Trying to draw more animation frames than the browser can handle can lock it up or cause it to terminate your script. Also if the user is viewing a different tab or is in another window; burning the user’s CPU on animation they don’t even see is just squandering their resources.

Luckily, much like debouncing and throttling for user input and ajax calls, there is something we can do. HTML5 provides a neat solution for animation.  The requestAnimationFrame function allows you to put in a call-back which gets executed when the browser is ready to draw another frame. This allows the browser to throttle the animation based on the current CPU load and whether the canvas is on screen or not, resulting in a far better performance and a much lower resource usage.

However, some older browsers don’t support requestAnimationFrame, but we can use the following code to detect if they do, and if they don’t, run though some earlier implementations and finally a fall-back method to ensure we can still use the function:

[code lang=”javascript” title=”Setting up timing function”]
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function () {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function ( callback,element) {
window.setTimeout(callback, 1000 / 60); // Fallback timeout
};
})();
}
[/code]

To use this function we need to create an animation loop. Also if we separate our animated elements from our static elements (e.g. background) into different canvases, we only need to redraw the static elements when they change which is far less frequently.

For this we create two functions renderStatic and renderAnim; which are outside the scope of this article, but there are plenty of canvas examples to draw on. When the static elements require redrawing we just set the requiresRedraw variable to true.

Putting this altogether we end up with a animation loop looking similar to the following:

[code lang=”javascript” title=”Setting up animation callback”]
var isAnimating = false; // Is animation on or off?
var animateRunning = false; // Are we in the animation loop?
var requiresRedraw = true; // Do the static elements need to be redrawn?

function StartAnimating() { // Start animating/drawing
isAnimating = true;
if (!animateRunning) Draw(); // Only draw if we are not already drawing
}
function StopAnimating() { // Stop animating/drawing
isAnimating = false;
}

function Draw() {
if (isAnimating) { // Only draw if we are drawing
animateRunning = true;
try {
if (requiresRedraw) {
requiresRedraw = false;
renderStatic(); // function defined elsewhere
// which draws static elements
}
renderAnim(); // function defined elsewhere
// which draws animated elements
} catch (e) {
if (window.console && window.console.log)
window.console.log(e); // for debugging
}
requestAnimationFrame(Draw);
animateRunning = false;
}
}
[/code]

To start the drawing we can use StartAnimating() and to stop we can use StopAnimating()

Following this pattern should help you improve the performance of your HTML5 canvas app – while also reducing the load on your user’s computer. A double benefit!