JSFiddle - React, Tailwind, and code Playground
by alnitak
JavaScript
(function($) {
$.wait = function(t) {
return $.Deferred(function() {
setTimeout(this.resolve, t);
}).promise();
};
$.whenAll = function(a) {
return $.when.apply($, a);
};
$.memoize = function(factory, ctx) {
var cache = {};
return function(key) {
if (!(key in cache)) {
cache[key] = factory.call(ctx, key);
}
return cache[key];
};
};
$.imageLoader = $.memoize(function(url) {
return $.Deferred(function(def) {
var img = new Image();
img.onload = function() {
def.resolveWith(img, [img]);
};
img.onerror = function() {
def.rejectWith(img, [img]);
};
img.src = url;
}).promise();
});
(function() {
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
var ctx = canvas.getContext('2d');
// TODO - find a better way to cope with the fact that invalid
// values of "col" are ignored
$.colorToRGBA = $.memoize(function(col) {
ctx.clearRect(0, 0, 1, 1);
ctx.fillStyle = col;
ctx.fillRect(0, 0, 1, 1);
return $.makeArray(ctx.getImageData(0, 0, 1, 1).data);
});
})();
}(jQuery));
$.imageLoader('http://www.gravatar.com/avatar/dc8c4ddd99b446c28d2e1546c457e508?s=128&d=identicon&r=PG').done(function() {
console.log([this.width, this.height]);
}).fail(function() {
console.log('error');
});
console.log($.colorToRGBA('red'));