KineticJS is a great framework to manipulate canvas but when it comes to preload images for a project there’s no elegant way of doing this but creating your own code or using other libraries (most of them are either incomplete or are not maintained). The one I’ve using for some time is PreloadJS and since I am used to it I wanted to include it in my project to make things easier for me.
index.html
<!DOCTYPE HTML> <html> <head> <style> #container{ background-color: #222222; width: 40px; height: 40px; } </style> <script src="kinetic-v5.0.1.min.js"></script> </span><script src="preloadjs-0.4.1.min.js"></script> </head> <body> <div id="container"></div> <script src="app.js"></script> </body> </html>
app.js file
var layer, stage, assets, manifest, handleAssetsLoad; //fire this function when preload is finished handleAssetsLoad = function ( evt ) { // get the image object from the assets var imgObj = assets.getResult("image"); // create KineticJS Image var test = new Kinetic.Image({ x: 0, y: 0, width: 40, height: 40, image: imgObj, }); // add the shape to the layer layer.add(test); // add the layer to stage stage.add(layer); } // create the kineticjs stage stage = new Kinetic.Stage({ container: "dungeoneer", width: 40, height: 40 }); layer = new Kinetic.Layer(); // which files to load manifest = [ {id: "image", src: "image.jpg"} ]; //initialize PreloadJS assets = new createjs.LoadQueue(true, "images/"); assets.on("complete", handleAssetsLoad); assets.loadManifest(manifest);