Skip to content

Commit

Permalink
Allow 'sprite' to take stringified JSON of sprite data and image.
Browse files Browse the repository at this point in the history
  • Loading branch information
dcervelli authored and AndyMoreland committed Aug 19, 2016
1 parent 13a9015 commit 2a3d879
Showing 1 changed file with 53 additions and 22 deletions.
75 changes: 53 additions & 22 deletions js/style/image_sprite.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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);
Expand Down Expand Up @@ -76,4 +107,4 @@ ImageSprite.prototype.getSpritePosition = function(name) {
if (pos && this.img) return pos;

return new SpritePosition();
};
};

0 comments on commit 2a3d879

Please sign in to comment.