SSJX.CO.UK
Browser Games | Cybiko | Amiga | Applications | Windows Games | Python | Guides | Site Map

Tips And Ideas For Improving Your Javascript Games

This guide will give you tips and ideas on how to improve your Javascript / HTML5 games. For more general programming tips, click here.

Use Strict Mode

Putting "use strict"; at the top of your program forces a stricter subset of javascript. This will help make programs more secure with less chance chance of errors. A far better description is here.

The following will show an error as the variable 'total' has not been declared:

"use strict";

total=total+1;

The code below is better as we have declared the variable 'total' in advance:

"use strict";

var total;

total=total+1;

The advantage of enabling strict mode is that if we make a spelling mistake on a variable, it would be caught. Without strict, it would happily run but result in a miscalcuation which may not be noticed:

"use strict";

var total;
// Without Strict mode, the spelling mistake below would result in wrong total
total=toal+1;

Strict mode has other advantages but forcing you to declare variables is probably the most useful.

Use Sprite Sheets

In general, having one large sprite sheet works out to have a smaller file size than having multiple individual sprites. A bonus from doing this is that it also results in less connections to the web server that is serving the pages.

The following is adapted from Menastar. There is one sprite sheet for the player ship and the player direction is used to grab the correct sprite to display:

// The direction is used to select which sprite to display
ctx.drawImage(images.ship,player.direction*32,0,32,32,  player.x,player.y,32,32);

Don't Redraw Unless You Need Too

The slowest part of your program will probably be drawing and refreshing the display. For things such as menus, this can cause unnecessarily high CPU usage for a fairly static display. The way around this is to not refresh the display as often.

In Flex (and others) you can just drop the stage frame rate, for Javascript you can keep the frame rate the same but just not draw until needed:

// Main game function that is called each frame
function update()
{
	//..
	// Draw the title screen
	if (drawnow==1)
	{
		draw_title();
		drawnow=0;
	}
	//..
	// By adding a counter, we can still refresh the page but slowly.
}

The main advantages of doing this is that by lessening the cpu (or gpu) usage you will:

10/04/2017

Play-Asia.com - Buy Games & Codes for PS4, PS3, Xbox 360, Xbox One, Wii U and PC / Mac.
Support this site : Visit Play-Asia for games and accessories for new and classic games consoles!