Image caching thing and Canvas

This draws the canvas circles with caching of images

by Oleh Kotsubko

HTML

<body></body>

CSS

canvas { float: left; }

JavaScript

var createCache = function(requestFunction) {
    var cache = {};
    return function(key, callback) {
        if (!cache[key]) {
            cache[key] = $.Deferred(function(defer) {
                requestFunction(defer, key);
            }).promise();
        }
        console.log(cache[key]);
        return cache[key].done(drawImg);
    };
};


var loadImage = createCache(function(defer, url) {
    var image = new Image();
    function cleanUp() {
       image.onload = image.onerror = null;
    }
    
    defer.then(cleanUp, cleanUp);
    image.onload = function() {
        defer.resolve(url);
    };
    image.onerror = defer.reject;
    image.src = url;
});


var drawImg = function(img) {
    var tmpCanvas = document.createElement('canvas'),
        tmpCtx = tmpCanvas.getContext('2d'),
        image = new Image();
    
    //console.log(img + ' loaded');
    
    image.src = img;
    console.log(image);
    tmpCanvas.width = image.width*6;
    tmpCanvas.height = image.height*6;
    
    // draw the cached images to temporary canvas and return the context
    tmpCtx.save();
        tmpCtx.beginPath();
            tmpCtx.arc(2*64, 2*64, 2*64, 0, Math.PI*2, true);
        tmpCtx.closePath();
        tmpCtx.clip();

    tmpCtx.drawImage(image, 0, 0, 4*64+2, 4*64+2);
    
        tmpCtx.beginPath();
            tmpCtx.arc(0, 0, 2, 0, Math.PI*2, true);
            tmpCtx.clip();
        tmpCtx.closePath();
    tmpCtx.restore();

    $('body').append(tmpCanvas);
};


var cacheImgs = function() {
    var imgs = [
        //'http://profile.ak.fbcdn.net/hprofile-ak-snc4/211728_608707040_573813586_n.jpg',
        'https://graph.facebook.com/649650002/picture?type=square',
        'https://graph.facebook.com/591963596/picture?type=square',
        'https://graph.facebook.com/531664351/picture?type=square'
    ];
    
    for (var i = 0; i < imgs.length; i++) {
        var img = loadImage(imgs[i])/*.done(drawImg(imgs[i]))*/;
        //console.log(img)
        // .done...