HTML5 Game Asset Manager and Loading Screen
Its important initialize a game if and when it is ready. I probably spent probably about two weeks looking for examples of this idea.One thing I was hope to get from this process was a way accurately update the loading and give the user a percent of when the game has loaded.For accurately updated the loading bar the best I have come up with is to have counter based on the number of assets and after each assets is loaded update the bar. The following setup is for the start button to change when the assets are loaded.
Follow code is taken directly from the example on HTML5 Rocks but I collected it into a single script and it proved to be very useful. I was working on some logic to queue not only images but sounds because more often than not audio files are larger than image files. Keep in mind though there is not a universal format that is supported like images.
Resources
Assets Loading in HTML5 Game Development
Simple Asset Management for HTML5 Games - HTML5 Rocks
Gopherwood Studios Blog: Loading HTML5 Game Assets
<button><span class="label" id="Gamer">Loading</span></button>
<script> (function () { function AssetManager() { this.successCount = 0; this.errorCount = 0; this.downloadQueue = []; this.cache = {}; } AssetManager.prototype.queueDownload = function (path) { this.downloadQueue.push(path); } AssetManager.prototype.downloadAll = function (downloadCallback) { for (var i = 0; i < this.downloadQueue.length; i++) { var path = this.downloadQueue[i]; var img = new Image(); var self = this; img.addEventListener("load", function () { console.log(this.src + ' is loaded'); self.successCount += 1; if (self.isDone()) { downloadCallback(); } }, false); img.addEventListener("error", function () { self.errorCount += 1; if (self.isDone()) { downloadCallback(); } }, false); img.src = path; this.cache[path] = img; } } AssetManager.prototype.isDone = function () { return (this.downloadQueue.length == this.successCount + this.errorCount); } AssetManager.prototype.getAsset = function (path) { return this.cache[path]; } var ASSET_MANAGER = new AssetManager(); //Example of use... ASSET_MANAGER.queueDownload('images/landscape.png'); ASSET_MANAGER.downloadAll(function(){}); //Change a Button to be enabled! if (ASSET_MANAGER.isDone) { document.getElementById("Gamer").innerHTML = "Play"; } })(); </script>
Resources
Assets Loading in HTML5 Game Development
Simple Asset Management for HTML5 Games - HTML5 Rocks
Gopherwood Studios Blog: Loading HTML5 Game Assets