/
stitches.js
326 lines (282 loc) · 11.8 KB
/
stitches.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// ## Stitches - HTML5 Sprite Sheet Generator
//
// [http://draeton.github.com/stitches](http://draeton.github.com/stitches)
//
// Copyright 2011, Matthew Cobbs
// Licensed under the MIT license.
//
/*global jQuery, Stitches, Modernizr */
(function (window, $, Modernizr) {
"use strict";
// ## Stitches namespace
//
// Holds all methods
var S = window.Stitches = (function () {
/* Some configuration defaults */
var defaults = {
"jsdir": "js",
"prefix": "sprite",
"padding": 10,
"dataURI": false
};
return {
// ### init
//
// Readies everything for user interaction.
//
// @param {jQuery} $elem A wrapped DOM node
// @param {Object} config An optional settings object
init: function ($elem, config) {
S.settings = $.extend({}, defaults, config);
S.iconQueue = [];
S.topics = {};
S.Page.$elem = $elem;
/* setup subscriptions */
S.sub("page.error", S.Page.errorHandler);
S.sub("page.init.done", S.Page.fetchTemplates);
S.sub("page.templates.done", S.Page.render);
S.sub("page.render.done", S.checkAPIs);
S.sub("page.apis.done", S.Page.bindDragAndDrop);
S.sub("page.apis.done", S.Page.bindButtons);
S.sub("page.apis.done", S.Page.bindCabinet);
S.sub("page.apis.done", S.Page.bindOptions);
S.sub("page.apis.done", S.Page.subscribe);
S.sub("page.drop.done", S.File.queueFiles);
S.sub("file.queue.done", S.File.queueIcons);
S.sub("file.icon.done", S.Page.addIcon);
S.sub("file.remove.done", S.Page.removeIcon);
S.sub("file.unqueue", S.File.unqueueIcon);
S.sub("file.unqueue.all", S.File.unqueueAllIcons);
S.sub("sprite.generate", S.generateStitches);
/* notify */
S.pub("page.init.done");
},
// ### sub
//
// Subscribe to a topic
//
// @param {String} topic The subscription topic name
// @param {Function} fn A callback to fire
sub: function (topic, fn) {
var callbacks = S.topics[topic] || $.Callbacks("stopOnFalse");
if (fn) {
callbacks.add(fn);
}
S.topics[topic] = callbacks;
},
// ### unsub
//
// Unsubscribe from a topic
//
// @param {String} topic The subscription topic name
// @param {Function} fn A callback to remove
unsub: function (topic, fn) {
var callbacks = S.topics[topic];
if (callbacks) {
callbacks.remove(fn);
}
},
// ### pub
//
// Publish a topic
//
// @param {String} topic The subscription topic name
pub: function (topic) {
var callbacks = S.topics[topic],
args = Array.prototype.slice.call(arguments, 1);
if (callbacks) {
callbacks.fire.apply(callbacks, args);
}
},
// ### checkAPIs
//
// Load supporting libraries for browsers with no native support. Uses
// Modernizr to check for drag-and-drop, FileReader, and canvas
// functionality.
checkAPIs: function () {
Modernizr.load([
{
test: typeof FileReader !== "undefined" && Modernizr.draganddrop,
nope: S.settings.jsdir + "/dropfile/dropfile.js"
},
{
test: Modernizr.canvas,
nope: S.settings.jsdir + "/flashcanvas/flashcanvas.js",
complete: function () {
if (typeof FileReader !== "undefined" && Modernizr.draganddrop && Modernizr.canvas) {
S.pub("page.apis.done");
} else {
S.pub("page.error", new Error("Required APIs are not present."));
}
}
}
]);
},
// ### generateStitches
//
// Positions all of the icons from the $filelist on the canvas;
// crate the sprite link and the stylesheet link;
// updates button state
//
// @param {[Icon]} looseIcons An Icon array of images to place
generateStitches: function (looseIcons) {
var placedIcons = S.positionImages(looseIcons);
var sprite = S.makeStitches(placedIcons);
var stylesheet = S.makeStylesheet(placedIcons, sprite);
/* notify */
S.pub("sprite.generate.done", sprite, stylesheet);
},
// ### positionImages
//
// Position all of the images in the `looseIcons` array within the canvas
//
// @param {[Icon]} looseIcons An Icon array of images to place
// @return {[Icon]} The placed images array
positionImages: function (looseIcons) {
var placedIcons = [];
/* reset position of icons */
$(looseIcons).each(function (idx, icon) {
icon.x = icon.y = 0;
icon.isPlaced = false;
});
/* reverse sort by area */
looseIcons = looseIcons.sort(function (a, b) {
if (b.area === a.area) {
return b.name > a.name ? 1 : -1;
} else {
return b.area - a.area;
}
});
/* find the ideal sprite for this set of icons */
S.canvas = S.Icons.idealCanvas(looseIcons);
/* try to place all of the icons on the ideal canvas */
S.Icons.placeIcons(looseIcons, placedIcons, S.canvas);
/* trim empty edges */
S.Icons.cropCanvas(placedIcons, S.canvas);
/* notify and return */
S.pub("sprite.position.done", placedIcons);
return placedIcons;
},
// ### makeStitches
//
// Draw images on canvas
//
// @param {[Icon]} The placed images array
// @return {String} The sprite image data URL
makeStitches: function (placedIcons) {
var context, data;
/* this block often fails as a result of the cross-
domain blocking in browses for access to write
image data to the canvas */
try {
context = S.canvas.getContext('2d');
$(placedIcons).each(function (idx, icon) {
context.drawImage(icon.image, icon.x, icon.y);
});
/* create image link */
data = S.canvas.toDataURL("image/png");
} catch (e) {
S.pub("page.error", e);
}
/* notify and return */
S.pub("sprite.image.done", data);
return data;
},
// ### makeStylesheet
//
// Create stylesheet text
//
// @param {[Icon]} The placed images array
// @param {String} The sprite data URI string
// @return {String} The sprite stylesheet
makeStylesheet: function (placedIcons, sprite) {
/* sort by name for css output */
placedIcons = placedIcons.sort(function (a, b) {
return a.name < b.name ? -1 : 1;
});
var prefix = S.settings.prefix;
var backgroundImage
if (S.settings.dataURI) {
backgroundImage = sprite;
} else {
backgroundImage = "download.png";
}
var css = [
"." + prefix + " {",
" background: url(" + backgroundImage + ") no-repeat;",
"}\n"
];
$(placedIcons).each(function (idx, icon) {
css = css.concat([
"." + prefix + "-" + icon.name + " {",
" width: " + icon.image.width + "px;",
" height: " + icon.image.height + "px;",
" background-position: -" + icon.x + "px -" + icon.y + "px;",
"}\n"
]);
});
/* create stylesheet link */
var data = "data:text/plain," + encodeURIComponent(css.join("\n"));
/* notify and return */
S.pub("sprite.stylesheet.done", data);
return data;
},
// ### dataToObjectURL
//
// Convert base64 data or raw binary data to an object URL
// See: http://stackoverflow.com/a/5100158/230483
//
// @param {String} dataURI
// @return {String} The object URL
dataToObjectURL: function (dataURI) {
var dataParts = dataURI.split(',');
var byteString;
// convert base64 to raw binary data held in a string
if (dataParts[0].indexOf('base64') >= 0) {
byteString = atob(dataParts[1]);
} else {
byteString = unescape(dataParts[1]);
}
// separate out the mime component
var mimeString = dataParts[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var bl = byteString.length;
var ab = new ArrayBuffer(bl);
var ia = new Uint8Array(ab);
var i;
for (i = 0; i < bl; i++) {
ia[i] = byteString.charCodeAt(i);
}
// get the blob and create an object URL
var blob = S.createBlob(ab, mimeString);
var url = S.createObjectURL(blob);
return url;
},
// ### createBlob
//
// Polyfill
createBlob: function (arrayBuffer, mimeString) {
var BlobBuilder = BlobBuilder || WebKitBlobBuilder;
if (!BlobBuilder) {
throw new Error("BlobBuilder is unsupported.")
}
var bb = new BlobBuilder();
bb.append(arrayBuffer);
return bb.getBlob(mimeString);
},
// ### createObjectURL
//
// Polyfill
createObjectURL: function (file) {
if (window.URL && window.URL.createObjectURL) {
return window.URL.createObjectURL(file);
}
if (window.webkitURL && window.webkitURL.createObjectURL) {
return window.webkitURL.createObjectURL(file);
}
/* if we reached here, it's unsupported */
throw new Error("createObjectURL is unsupported.")
}
};
})();
})(window, jQuery, Modernizr);