Over a million developers have joined DZone.

How They Did It: Command and Conquer in HTML5 Canvas

DZone 's Guide to

How They Did It: Command and Conquer in HTML5 Canvas

· Web Dev Zone ·
Free Resource

You read that right: Command and Conquer entirely in HTML5, running on 69k of JavaScript.

Not by some game publishing house, either. One guy wrote it, the apparently awesome Aditya Ravi Shankar -- whose tutorial for making Breakout in Canvas is also worth a look.

The game actually works (though not every vehicle type etc. is included yet). Aditya code it as a learning experience, though, specifically (as he says) to practice these Canvas/JavaScript techniques:

  1. Using images to recreate the sidebar and game interface
  2. Using mouse input for unit selection, panning, attacking and user input
  3. Using images as sprites for unit and building animation
  4. A lot more sounds for units and buildings
  5. Using a finite state machine for handling unit commands, movement, attacking etc.
  6. Using path finding (A*) to navigate around obstructions like buildings, mountains and trees
  7. Using hidden canvas’s for things like fog of war and image manipulation

These are some serious tasks for poor old DOM-designed JavaScript. But Aditya pulled it off.

Here's a little peek at that fog of war Canvas trick:

            fogCanvas: document.createElement("canvas"),
            canvasWidth: 128,
            canvasHeight: 128,
            init: function () {
                this.fogContext = this.fogCanvas.getContext("2d"), this.fogContext.fillStyle = "rgba(0,0,0,1)", this.fogContext.fillRect(0, 0, this.canvasWidth, this.canvasHeight)
            draw: function () {
                var a = this.fogCanvas,
                    c = this.fogContext,
                    e = d.currentLevel.mapImage;
                c.save(), c.scale(this.canvasWidth / e.width, this.canvasHeight / e.height), c.fillStyle = "rgba(200,200,200,1)";
                for (var f = d.units.length - 1; f >= 0; f--) {
                    var g = d.units[f];
                    if (g.team == d.currentLevel.team || g.bulletFiring) c.beginPath(), c.globalCompositeOperation = "destination-out", c.arc((Math.floor(g.x) + .5) * d.gridSize, (Math.floor(g.y) + .5) * d.gridSize, (g.sight + .5) * d.gridSize, 0, 2 * Math.PI, !1), c.fill()

(That's about 10% from the bottom of the JavaScript file, after unminifying at jsbeautifier.org.)

Besides, the bullet-points quoted above, Aditya's C&C development post doesn't include too many insights -- except for some detailed discussion of pathfinding in JavaScript, which is always a cool CS-ey topic.

So enjoy the game, check out the JavaScript (definitely after unminifying..whew), and Aditya's 'how I did it' page. And command; and conquer...


Update: the source is now on github.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}