diff --git a/js/style/image_sprite.js b/js/style/image_sprite.js index 1d75cab23fa..f8c1f2327ca 100644 --- a/js/style/image_sprite.js +++ b/js/style/image_sprite.js @@ -9,27 +9,8 @@ module.exports = ImageSprite; function ImageSprite(base) { this.base = base; - this.retina = browser.devicePixelRatio > 1; - var format = this.retina ? '@2x' : ''; - - ajax.getJSON(normalizeURL(base, format, '.json'), function(err, data) { - if (err) { - this.fire('error', {error: err}); - return; - } - - this.data = data; - if (this.img) this.fire('load'); - }.bind(this)); - - ajax.getImage(normalizeURL(base, format, '.png'), function(err, img) { - if (err) { - this.fire('error', {error: err}); - return; - } - - // premultiply the sprite + var premultiply = function (img) { var data = img.getData(); var newdata = img.data = new Uint8Array(data.length); for (var i = 0; i < data.length; i += 4) { @@ -39,10 +20,60 @@ function ImageSprite(base) { newdata[i + 2] = data[i + 2] * alpha; newdata[i + 3] = data[i + 3]; } + }; + + var loadImage = function (err, img) { + if (err) { + this.fire('error', {error: err}); + return; + } + premultiply(img); this.img = img; if (this.data) this.fire('load'); - }.bind(this)); + }.bind(this); + + function loadRemote() { + this.retina = browser.devicePixelRatio > 1; + var format = this.retina ? '@2x' : ''; + ajax.getJSON(normalizeURL(base, format, '.json'), function(err, data) { + if (err) { + this.fire('error', {error: err}); + return; + } + + this.data = data; + if (this.img) this.fire('load'); + }.bind(this)); + + ajax.getImage(normalizeURL(base, format, '.png'), loadImage); + } + + function loadLocal() { + var parsedBase = JSON.parse(this.base); + this.data = parsedBase.data; + + var img = new Image(); + img.getData = function() { + var canvas = document.createElement('canvas'); + var context = canvas.getContext('2d'); + canvas.width = img.width; + canvas.height = img.height; + context.drawImage(img, 0, 0); + return context.getImageData(0, 0, img.width, img.height).data; + }; + img.onload = function() { + loadImage(null, img); + }; + this.img = img; + img.src = parsedBase.url; + } + + if (base.charAt(0) !== "{") { + loadRemote.bind(this)(); + } else { + loadLocal.bind(this)(); + } } ImageSprite.prototype = Object.create(Evented); @@ -76,4 +107,4 @@ ImageSprite.prototype.getSpritePosition = function(name) { if (pos && this.img) return pos; return new SpritePosition(); -}; +}; \ No newline at end of file