summaryrefslogtreecommitdiff
path: root/public/js/mp/resource.js
blob: f348a894cbf20e9181420ef6c87ef74e964b5eb0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"use strict";
var mp = function(mp) {
    mp.resource = {
        loadImage: loadImage
    };

    /*
     * Quick compatability workaround
     *  node testing environment needs new Canvas() and won't tolerate document.createElement("canvas")
     *  A createCanvas method is therefore provided in its sandbox which can be quickly checked to determine the method needed
     */
    var createCanvas = "createCanvas" in document ? document.createCanvas : function() { return document.createElement("canvas"); };

    var canvas = createCanvas();
    var context = canvas.getContext("2d");

    /*
     * Load in an image given a URL.
     * The provided callback will fire when loading is complete.
     * The parameters will be false and the the imageData if successful, and false and the error otherwise.
     */
    function loadImage(url, callback) {
        var image = new Image();
        image.onload = function() {
            canvas.width = image.width;
            canvas.height = image.height;
            context.drawImage(image, 0, 0);
            callback(false, context.getImageData(0, 0, image.width, image.height));
        };
        image.onerror = function(err) {
            callback(true, err);
        };
        image.src = url;
    }
    return mp;
}(mp || {});