Image loader plugin for soma.js

| 2 min read

Now that we can easily create plugins for soma.js, I've created an image loader plugin.

I've used PxLoader as a base and before any explanation, it looks like that:

The advantage of using the plugin is that you are able to listen to these events anywhere in your application: in a wire, in the framework instance or a model.

Here is how to instantiate the plugin.

this.createPlugin(SomaImageLoader, "assets/config.json");

The plugin will first load the config file, you can add an event to know when it will be loaded. And again, anywhere in the application, a model to manage your assets would make complete sense.

this.addEventListener(SomaImageLoaderEvent.CONFIG\_LOADED, this.configLoadedHandler.bind(this)); 

Once the config is loaded, you can dispatch a command to start the loading.

this.dispatchEvent(new SomaImageLoaderEvent(SomaImageLoaderEvent.START)); 

The plugin will catch the start event and start the loading. To retrieve the images and use them, you can either listen to an "image complete" event, or wait that everything is loaded and listen to a "queue complete event".

this.addEventListener(SomaImageLoaderEvent.ITEM\_COMPLETE, this.itemCompleteHandler.bind(this)); this.addEventListener(SomaImageLoaderEvent.QUEUE\_COMPLETE, this.completeHandler.bind(this)); 
itemCompleteHandler: function(event) {
// notification received when an item is loaded
console.log('> item complete', event.params.completed, "/", event.params.total);
console.log(' id:', event.params.loader.id);
console.log(' loader:', event.params.loader);
console.log(' data:', event.params.data);
// draw image loaded in a canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(event.params.data, 0, 0);
},
completeHandler: function(event) {
// notification received when all items are loaded
this.log('> complete');
// draw all images loaded in a canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(event.params.data['img1'], 0, 0);
ctx.drawImage(event.params.data['img2'], 100, 50);
ctx.drawImage(event.params.data['img3'], 200, 100);
ctx.drawImage(event.params.data['img4'], 300, 150);
ctx.drawImage(event.params.data['img5'], 400, 200);
},

You don't have to use a config json, all these operation can be done manually if you wish to.

var plugin = this.createPlugin(SomaImageLoader);
// plugin.loadConfig("assets/config.json");
plugin.addImage("myImage1", "assets/images/img1.jpg");
plugin.addImage("myImage2", "assets/images/img2.jpg");
plugin.start();

You can find the plugin on the soma.js site in the "plugins section" or on the github repo.

You will find both a native version and a Mootools version.