Working with KineticJS and PreloadJS – preload images and display them on canvas

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);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s