Game Development Reference
In-Depth Information
updateDOM();
},
get: function(key) {
var dict = dictionaries[lang] || dictionaries[defaultLang];
return ""+dict[key];
},
updateDOM: updateDOM
}
}();
$(document).ready(i18n.init);
Pure DOM vs. canvas-based game
There are mainly two ways to develop a game.
The first solution, which we call “Pure DOM,” is to decompose the game into multiple HTML elements (for
each game atomic element) and to use the power of CSS to style this game. This is what we did with our
chess game.
Another solution is to use a big canvas to run the game. Canvas allows you to manipulate bitmap pixels in
JavaScript. It provides a low-level API with different draw methods and properties that we will explore.
Both solutions are viable, but do not cover the same needs. The solution depends on the game type.
Overview of the Canvas API
To manipulate the canvas API, you need to get a context. It can be "2d" for the Canvas 2D, "webgl" for
WebGL, and so forth. For the Canvas 2D API, you retrieve it with
var ctx = document.getElementById("mycanvasid").getContext("2d");
You can now access to the full Canvas 2D API from the ctx variable.
Listing 3-16 is an example of the canvas code that I used in Same Game Gravity . It draws a piece of
the game.
Listing 3-16. Canvas Code from Same Game Gravity
var canvas = document.getElementById("mycanvasid");
var ctx = canvas.getContext("2d");
function drawBrick = function(brick, size) {
if(!size) size = 1;
ctx.save(); // Save the current ctx state
ctx.translate(brick.x, brick.y); // change origin and units
ctx.scale(brick.w, brick.h); // to work with easy values
var gradient = ctx.createLinearGradient(0,0,0,1);
gradient.addColorStop(0, brick.colorLighter);
gradient.addColorStop(0.6, brick.color);
ctx.fillStyle = gradient; // the fillStyle is a gradient
ctx.clearRect(0,0,1,1); // empty the rect
 
Search WWH ::




Custom Search