A good example is found in reading a book about the development of a HTML5 game, which allows for a more in-depth understanding of object-oriented development. This object is implemented by drawing an image from a CSS sprite into the canvas. First create a Spritesheet object with the following code:
var spritesheet = new function () {This.map = {};this.load = function (spritedata,callback) {this.image = new image (); this.im Age.onload = CALLBACK;THIS.IMAGE.SRC = "Images/sprites.png";}; This.draw = function (ctx,sprite,x,y,frame) {var s = this.map[sprite];if (!frame) {frame = 0;}; Ctx.drawimage (This.image, S.SX+FRAME*S.W, S.sy, S.W, s.h, X, Y, S.W, s.h);};}
The new function () {} is used first, guaranteeing that only one instance will be created.
Next to the object, it is bound to two methods and a property through this. The Load method loads the image, passes two parameters, and the first parameter is the image information, the position of the image to be drawn in the sprite, and the size of the position on the canvas. Note the use of callback, which is this.image.onload = Callbak; Executes the incoming callback function when the image is loaded.
The draw method is used to draw the image, the context of the canvas, the image object information to be drawn, and the location of the image.
The logical construction of this object is relatively complex, the basic idea is to customize the Load method, the Load method to complete the loading of image information. The image information here refers to the position, size, etc. of the image in the sprite.
The method code for using the object is as follows:
function Startgame () {spritesheet.load ({ship:{sx:0, sy:0, w:18, h:35, Frames:3}},function () {Spritesheet.draw (CTX, " Ship ", 0,0); Spritesheet.draw (CTX, "ship", 100,50); Spritesheet.draw (CTX, "Ship", 150,100, 1);});
Here, using the Load method, first pass in the relevant data of the desired section of the graph, and then call the object's draw method in the callback function to draw the image.
HTML5 Object-oriented game development Simple example Summary