-
Notifications
You must be signed in to change notification settings - Fork 73
/
jaws.js
4390 lines (3891 loc) · 139 KB
/
jaws.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Built at 2013-08-29 21:06:03 +0200 */
/**
* @fileOverview A jaws.Text object with word-wrapping functionality.
* @class jaws.Text
* @property {integer} x Horizontal position (0 = furthest left)
* @property {integer} y Vertical position (0 = top)
* @property {number} alpha Transparency: 0 (fully transparent) to 1 (no transparency)
* @property {number} angle Angle in degrees (0-360)
* @property {string} anchor String stating how to anchor the sprite to canvas; @see Sprite#anchor
* @property {string} text The actual text to be displayed
* @property {string} fontFace A valid font-family
* @property {number} fontSize The size of the text in pixels
* @property {string} textAlign "start", "end", "left", "right", or "center"
* @property {string} textBaseline "top", "bottom", "hanging", "middle", "alphabetic", or "ideographic"
* @property {number} width The width of the rect() containing the text
* @property {number} height The height of the rect() containing the text
* @property {string} style The style to draw the text: "normal", "bold" or italic"
* @property {boolean} wordWrap If word-wrapping should be attempted
* @property {string} shadowColor The color of the shadow for the text
* @property {number} shadowBlur The amount of shadow blur (length away from text)
* @property {number} shadowOffsetX The start of the shadow from initial x
* @property {number} shadowOffsetY The start of the shadow from initial y
* @example
* var text = new Text({text: "Hello world!", x: 10, y: 10})
*/
var jaws = (function(jaws) {
/**
* jaws.Text constructor
* @constructor
* @param {object} options An object-literal collection of constructor values
*/
jaws.Text = function(options) {
if (!(this instanceof arguments.callee))
return new arguments.callee(options);
this.set(options);
if (options.context) {
this.context = options.context;
}
else if (options.dom) { // No canvas context? Switch to DOM-based spritemode
this.dom = options.dom;
this.createDiv();
}
if (!options.context && !options.dom) { // Defaults to jaws.context or jaws.dom
if (jaws.context)
this.context = jaws.context;
else {
this.dom = jaws.dom;
this.createDiv();
}
}
};
/**
* The default values of jaws.Text properties
*/
jaws.Text.prototype.default_options = {
x: 0,
y: 0,
alpha: 1,
angle: 0,
anchor_x: 0,
anchor_y: 0,
anchor: "top_left",
damping: 1,
style: "normal",
fontFace: "serif",
fontSize: 12,
color: "black",
textAlign: "start",
textBaseline: "alphabetic",
text: "",
wordWrap: false,
width: function(){ return jaws.width; },
height: function() { return jaws.height; },
shadowColor: null,
shadowBlur: null,
shadowOffsetX: null,
shadowOffsetY: null,
_constructor: null,
dom: null
};
/**
* Overrides constructor values with defaults
* @this {jaws.Text}
* @param {object} options An object-literal collection of constructor values
* @returns {this}
* @see jaws.parseOptions
*/
jaws.Text.prototype.set = function(options) {
jaws.parseOptions(this, options, this.default_options);
if (this.anchor)
this.setAnchor(this.anchor);
this.cacheOffsets();
return this;
};
/**
* Returns a new instance based on the current jaws.Text object
* @private
* @this {jaws.Text}
* @returns {object} The newly cloned object
*/
jaws.Text.prototype.clone = function() {
var constructor = this._constructor ? eval(this._constructor) : this.constructor;
var new_sprite = new constructor(this.attributes());
new_sprite._constructor = this._constructor || this.constructor.name;
return new_sprite;
};
/**
* Rotate sprite by value degrees
* @this {jaws.Text}
* @param {number} value The amount of the rotation
* @returns {this} Current function scope
*/
jaws.Text.prototype.rotate = function(value) {
this.angle += value;
return this;
};
/**
* Forces a rotation-angle on sprite
* @this {jaws.Text}
* @param {number} value The amount of the rotation
* @returns {this} Current function instance
*/
jaws.Text.prototype.rotateTo = function(value) {
this.angle = value;
return this;
};
/**
* Move object to position x, y
* @this {jaws.Text}
* @param {number} x The x position to move to
* @param {number} y The y position to move to
* @returns {this} Current function instance
*/
jaws.Text.prototype.moveTo = function(x, y) {
this.x = x;
this.y = y;
return this;
};
/**
* Modify x and/or y by a fixed amount
* @this {jaws.Text}
* @param {type} x The additional amount to move x
* @param {type} y The additional amount to move y
* @returns {this} Current function instance
*/
jaws.Text.prototype.move = function(x, y) {
if (x)
this.x += x;
if (y)
this.y += y;
return this;
};
/**
* Sets x
* @param {number} value The new x value
* @returns {this} The current function instance
*/
jaws.Text.prototype.setX = function(value) {
this.x = value;
return this;
};
/**
* Sets y
* @param {number} value The new y value
* @returns {this} The current function instance
*/
jaws.Text.prototype.setY = function(value) {
this.y = value;
return this;
};
/**
* Position sprites top on the y-axis
* @param {number} value
* @returns {this} The current function instance
*/
jaws.Text.prototype.setTop = function(value) {
this.y = value + this.top_offset;
return this;
};
/**
* Position sprites bottom on the y-axis
* @param {number} value
* @returns {this} The current function instance
*/
jaws.Text.prototype.setBottom = function(value) {
this.y = value - this.bottom_offset;
return this;
};
/**
* Position sprites left side on the x-axis
* @param {number} value
* @returns {this} The current function instance
*/
jaws.Text.prototype.setLeft = function(value) {
this.x = value + this.left_offset;
return this;
};
/**
* Position sprites right side on the x-axis
* @param {number} value
* @returns {this} The current function instance
*/
jaws.Text.prototype.setRight = function(value) {
this.x = value - this.right_offset;
return this;
};
/**
* Set new width.
* @param {number} value The new width
* @returns {jaws.Rect}
*/
jaws.Text.prototype.setWidth = function(value) {
this.width = value;
return this.cacheOffsets();
};
/**
* Set new height.
* @param {number} value The new height
* @returns {jaws.Rect}
*/
jaws.Text.prototype.setHeight = function(value) {
this.height = value;
return this.cacheOffsets();
};
/**
* Resize sprite by adding width or height
* @param {number} width
* @param {number} height
* @returns {jaws.Rect}
*/
jaws.Text.prototype.resize = function(width, height) {
this.width += width;
this.height += height;
return this.cacheOffsets();
};
/**
* Resize sprite to exact width/height
* @this {jaws.Text}
* @param {number} width
* @param {number} height
* @returns {jaws.Rect}
*/
jaws.Text.prototype.resizeTo = function(width, height) {
this.width = width;
this.height = height;
return this.cacheOffsets();
};
/**
* The anchor could be describe as "the part of the text will be placed at x/y"
* or "when rotating, what point of the of the text will it rotate round"
* @param {string} value
* @returns {this} The current function instance
* @example
* For example, a topdown shooter could use setAnchor("center") --> Place middle of the ship on x/y
* .. and a sidescroller would probably use setAnchor("center_bottom") --> Place "feet" at x/y
*/
jaws.Text.prototype.setAnchor = function(value) {
var anchors = {
top_left: [0, 0],
left_top: [0, 0],
center_left: [0, 0.5],
left_center: [0, 0.5],
bottom_left: [0, 1],
left_bottom: [0, 1],
top_center: [0.5, 0],
center_top: [0.5, 0],
center_center: [0.5, 0.5],
center: [0.5, 0.5],
bottom_center: [0.5, 1],
center_bottom: [0.5, 1],
top_right: [1, 0],
right_top: [1, 0],
center_right: [1, 0.5],
right_center: [1, 0.5],
bottom_right: [1, 1],
right_bottom: [1, 1]
};
if (anchors.hasOwnProperty(value)) {
this.anchor_x = anchors[value][0];
this.anchor_y = anchors[value][1];
this.cacheOffsets();
}
return this;
};
/**
* Save the object's dimensions
* @private
* @returns {this} The current function instance
*/
jaws.Text.prototype.cacheOffsets = function() {
this.left_offset = this.width * this.anchor_x;
this.top_offset = this.height * this.anchor_y;
this.right_offset = this.width * (1.0 - this.anchor_x);
this.bottom_offset = this.height * (1.0 - this.anchor_y);
if (this.cached_rect)
this.cached_rect.resizeTo(this.width, this.height);
return this;
};
/**
* Returns a jaws.Rect() perfectly surrouning text.
* @returns {jaws.Rect}
*/
jaws.Text.prototype.rect = function() {
if (!this.cached_rect && this.width)
this.cached_rect = new jaws.Rect(this.x, this.y, this.width, this.height);
if (this.cached_rect)
this.cached_rect.moveTo(this.x - this.left_offset, this.y - this.top_offset);
return this.cached_rect;
};
/**
* Make this sprite a DOM-based <div> sprite
* @private
*/
jaws.Text.prototype.createDiv = function() {
this.div = document.createElement("div");
this.div.style.position = "absolute";
this.div.style.width = this.width + "px";
this.div.style.height = this.height + "px";
this.div.style.fontSize = this.fontSize + "px";
this.div.style.fontFamily = this.fontFace;
this.div.style.textShadow = (this.shadowOffsetX || "0") + "px "
+ (this.shadowOffsetY || "0") + "px " + (this.shadowBlur || "0")
+ "px " + (this.shadowColor || "");
if (this.textAlign === "start")
this.div.style.textAlign = "left";
else if (this.textAlign === "end")
this.div.style.textAlign = "right";
else
this.div.style.textAlign = this.textAlign;
if (this.textBaseline === "top")
this.div.style.verticalAlign = "super";
else if (this.textBaseline === "hanging")
this.div.style.verticalAlign = "text-top";
else if (this.textBaseline === "alphabetic")
this.div.style.verticalAlign = "bottom";
else if (this.div.style.verticalAlign === "ideographic")
this.div.style.verticalAlign = "text-bottom";
else
this.div.style.verticalAlign = this.textBaseline;
if (this.div.innerText) {
this.div.innerText = this.text;
}
else {
this.div.textContent = this.text;
}
if (this.dom) {
this.dom.appendChild(this.div);
}
this.updateDiv();
};
/**
* Update properties for DOM-based sprite
* @private
*/
jaws.Text.prototype.updateDiv = function() {
this.div.style.left = this.x + "px";
this.div.style.top = this.y + "px";
var transform = "";
transform += "rotate(" + this.angle + "deg) ";
this.div.style.MozTransform = transform;
this.div.style.WebkitTransform = transform;
this.div.style.OTransform = transform;
this.div.style.msTransform = transform;
this.div.style.transform = transform;
return this;
};
/**
* Draw sprite on active canvas or update its DOM-properties
* @this {jaws.Text}
* @returns {this} The current function instance
*/
jaws.Text.prototype.draw = function() {
if (this.dom) {
return this.updateDiv();
}
this.context.save();
if (this.angle !== 0) {
this.context.rotate(this.angle * Math.PI / 180);
}
this.context.globalAlpha = this.alpha;
this.context.translate(-this.left_offset, -this.top_offset); // Needs to be separate from above translate call cause of flipped
this.context.fillStyle = this.color;
this.context.font = this.style + " " + this.fontSize + "px " + this.fontFace;
this.context.textBaseline = this.textBaseline;
this.context.textAlign = this.textAlign;
if (this.shadowColor)
this.context.shadowColor = this.shadowColor;
if (this.shadowBlur)
this.context.shadowBlur = this.shadowBlur;
if (this.shadowOffsetX)
this.context.shadowOffsetX = this.shadowOffsetX;
if (this.shadowOffsetY)
this.context.shadowOffsetY = this.shadowOffsetY;
var oldY = this.y;
var oldX = this.x;
if (this.wordWrap)
{
var words = this.text.split(' ');
var nextLine = '';
for (var n = 0; n < words.length; n++)
{
var testLine = nextLine + words[n] + ' ';
var measurement = this.context.measureText(testLine);
if (this.y < oldY + this.height)
{
if (measurement.width > this.width)
{
this.context.fillText(nextLine, this.x, this.y);
nextLine = words[n] + ' ';
this.y += this.fontSize;
}
else {
nextLine = testLine;
}
this.context.fillText(nextLine, this.x, this.y);
}
}
}
else
{
if (this.context.measureText(this.text).width < this.width)
{
this.context.fillText(this.text, this.x, this.y);
}
else
{
var words = this.text.split(' ');
var nextLine = ' ';
for (var n = 0; n < words.length; n++)
{
var testLine = nextLine + words[n] + ' ';
if (this.context.measureText(testLine).width < Math.abs(this.width - this.x))
{
this.context.fillText(testLine, this.x, this.y);
nextLine = words[n] + ' ';
nextLine = testLine;
}
}
}
}
this.y = oldY;
this.x = oldX;
this.context.restore();
return this;
};
/**
* Returns sprite as a canvas context.
* (For certain browsers, a canvas context is faster to work with then a pure image.)
* @public
* @this {jaws.Text}
*/
jaws.Text.prototype.asCanvasContext = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var context = canvas.getContext("2d");
context.mozImageSmoothingEnabled = jaws.context.mozImageSmoothingEnabled;
this.context.fillStyle = this.color;
this.context.font = this.style + this.fontSize + "px " + this.fontFace;
this.context.textBaseline = this.textBaseline;
this.context.textAlign = this.textAlign;
if (this.shadowColor)
this.context.shadowColor = this.shadowColor;
if (this.shadowBlur)
this.context.shadowBlur = this.shadowBlur;
if (this.shadowOffsetX)
this.context.shadowOffsetX = this.shadowOffsetX;
if (this.shadowOffsetY)
this.context.shadowOffsetY = this.shadowOffsetY;
var oldY = this.y;
var oldX = this.x;
if (this.wordWrap)
{
var words = this.text.split(' ');
var nextLine = '';
for (var n = 0; n < words.length; n++)
{
var testLine = nextLine + words[n] + ' ';
var measurement = this.context.measureText(testLine);
if (this.y < oldY + this.height)
{
if (measurement.width > this.width)
{
this.context.fillText(nextLine, this.x, this.y);
nextLine = words[n] + ' ';
this.y += this.fontSize;
}
else {
nextLine = testLine;
}
this.context.fillText(nextLine, this.x, this.y);
}
}
}
else
{
if (this.context.measureText(this.text).width < this.width)
{
this.context.fillText(this.text, this.x, this.y);
}
else
{
var words = this.text.split(' ');
var nextLine = ' ';
for (var n = 0; n < words.length; n++)
{
var testLine = nextLine + words[n] + ' ';
if (this.context.measureText(testLine).width < Math.abs(this.width - this.x))
{
this.context.fillText(testLine, this.x, this.y);
nextLine = words[n] + ' ';
nextLine = testLine;
}
}
}
}
this.y = oldY;
this.x = oldX;
return context;
};
/**
* Returns text as a canvas
* @this {jaws.Text}
*/
jaws.Text.prototype.asCanvas = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var context = canvas.getContext("2d");
context.mozImageSmoothingEnabled = jaws.context.mozImageSmoothingEnabled;
this.context.fillStyle = this.color;
this.context.font = this.style + this.fontSize + "px " + this.fontFace;
this.context.textBaseline = this.textBaseline;
this.context.textAlign = this.textAlign;
if (this.shadowColor)
this.context.shadowColor = this.shadowColor;
if (this.shadowBlur)
this.context.shadowBlur = this.shadowBlur;
if (this.shadowOffsetX)
this.context.shadowOffsetX = this.shadowOffsetX;
if (this.shadowOffsetY)
this.context.shadowOffsetY = this.shadowOffsetY;
var oldY = this.y;
var oldX = this.x;
if (this.wordWrap)
{
var words = this.text.split(' ');
var nextLine = '';
for (var n = 0; n < words.length; n++)
{
var testLine = nextLine + words[n] + ' ';
var measurement = context.measureText(testLine);
if (this.y < oldY + this.height)
{
if (measurement.width > this.width)
{
context.fillText(nextLine, this.x, this.y);
nextLine = words[n] + ' ';
this.y += this.fontSize;
}
else {
nextLine = testLine;
}
context.fillText(nextLine, this.x, this.y);
}
}
}
else
{
if (context.measureText(this.text).width < this.width)
{
this.context.fillText(this.text, this.x, this.y);
}
else
{
var words = this.text.split(' ');
var nextLine = ' ';
for (var n = 0; n < words.length; n++)
{
var testLine = nextLine + words[n] + ' ';
if (context.measureText(testLine).width < Math.abs(this.width - this.x))
{
context.fillText(testLine, this.x, this.y);
nextLine = words[n] + ' ';
nextLine = testLine;
}
}
}
}
this.y = oldY;
this.x = oldX;
return canvas;
};
/**
* Returns Text's properties as a String
* @returns {string}
*/
jaws.Text.prototype.toString = function() {
return "[Text " + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.width + ", " + this.height + "]";
};
/**
* Returns Text's properties as a pure object
* @returns {object}
*/
jaws.Text.prototype.attributes = function() {
var object = this.options; // Start with all creation time properties
object["_constructor"] = this._constructor || "jaws.Text";
object["x"] = parseFloat(this.x.toFixed(2));
object["y"] = parseFloat(this.y.toFixed(2));
object["text"] = this.text;
object["alpha"] = this.alpha;
object["angle"] = parseFloat(this.angle.toFixed(2));
object["anchor_x"] = this.anchor_x;
object["anchor_y"] = this.anchor_y;
object["style"] = this.style;
object["fontSize"] = this.fontSize;
object["fontFace"] = this.fontFace;
object["color"] = this.color;
object["textAlign"] = this.textAlign;
object["textBaseline"] = this.textBaseline;
object["wordWrap"] = this.wordWrap;
object["width"] = this.width;
object["height"] = this.height;
return object;
};
/**
* Returns a JSON-string representing the properties of the Text.
* @returns {string}
*/
jaws.Text.prototype.toJSON = function() {
return JSON.stringify(this.attributes());
};
return jaws;
})(jaws || {});
// Support CommonJS require()
if (typeof module !== "undefined" && ('exports' in module)) {
module.exports = jaws.Text;
}
var jaws = (function(jaws) {
/**
* @fileOverview jaws.assets properties and functions
*
* Loads and processes image, sound, video, and json assets
* (Used internally by JawsJS to create <b>jaws.assets</b>)
*
* @class Jaws.Assets
* @constructor
* @property {boolean} bust_cache Add a random argument-string to assets-urls when loading to bypass any cache
* @property {boolean} fuchia_to_transparent Convert the color fuchia to transparent when loading .bmp-files
* @property {boolean} image_to_canvas Convert all image assets to canvas internally
* @property {string} root Rootdir from where all assets are loaded
* @property {array} file_type Listing of file postfixes and their associated types
* @property {array} can_play Listing of postfixes and (during runtime) populated booleans
*/
jaws.Assets = function Assets() {
if (!(this instanceof arguments.callee))
return new arguments.callee();
var self = this;
self.loaded = [];
self.loading = [];
self.src_list = [];
self.data = [];
self.bust_cache = false;
self.image_to_canvas = true;
self.fuchia_to_transparent = true;
self.root = "";
self.file_type = {};
self.file_type["json"] = "json";
self.file_type["wav"] = "audio";
self.file_type["mp3"] = "audio";
self.file_type["ogg"] = "audio";
self.file_type['m4a'] = "audio";
self.file_type['weba'] = "audio";
self.file_type['aac'] = "audio";
self.file_type['mka'] = "audio";
self.file_type['flac'] = "audio";
self.file_type["png"] = "image";
self.file_type["jpg"] = "image";
self.file_type["jpeg"] = "image";
self.file_type["gif"] = "image";
self.file_type["bmp"] = "image";
self.file_type["tiff"] = "image";
self.file_type['mp4'] = "video";
self.file_type['webm'] = "video";
self.file_type['ogv'] = "video";
self.file_type['mkv'] = "video";
var audioTest = new Audio();
var videoTest = document.createElement('video');
self.can_play = {};
self.can_play["wav"] = !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '');
self.can_play["ogg"] = !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '');
self.can_play["mp3"] = !!audioTest.canPlayType('audio/mpeg;').replace(/^no$/, '');
self.can_play["m4a"] = !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, '');
self.can_play["weba"] = !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '');
self.can_play["aac"] = !!audioTest.canPlayType('audio/aac;').replace(/^no$/, '');
self.can_play["mka"] = !!audioTest.canPlayType('audio/x-matroska;').replace(/^no$/, '');
self.can_play["flac"] = !!audioTest.canPlayType('audio/x-flac;').replace(/^no$/, '');
self.can_play["mp4"] = !!videoTest.canPlayType('video/mp4;').replace(/^no$/, '');
self.can_play["webm"] = !!videoTest.canPlayType('video/webm; codecs="vorbis"').replace(/^no$/, '');
self.can_play["ogv"] = !!videoTest.canPlayType('video/ogg; codecs="vorbis"').replace(/^no$/, '');
self.can_play["mkv"] = !!videoTest.canPlayType('video/x-matroska;').replace(/^no$/, '');
/**
* Returns the length of the resource list
* @public
* @returns {number} The length of the resource list
*/
self.length = function() {
return self.src_list.length;
};
/**
* Set root prefix-path to all assets
*
* @example
* jaws.assets.setRoot("music/").add(["music.mp3", "music.ogg"]).loadAll()
*
* @public
* @param {string} path-prefix for all following assets
* @returns {object} self
*/
self.setRoot = function(path) {
self.root = path
return self
}
/**
* Get one or more resources from their URLs. Supports simple wildcard (you can end a string with "*").
*
* @example
* jaws.assets.add(["song.mp3", "song.ogg"])
* jaws.assets.get("song.*") // -> Will return song.ogg in firefox and song.mp3 in IE
*
* @public
* @param {string|array} src The resource(s) to retrieve
* @returns {array|object} Array or single resource if found in cache. Undefined otherwise.
*/
self.get = function(src) {
if (jaws.isArray(src)) {
return src.map(function(i) {
return self.data[i];
});
}
else if (jaws.isString(src)) {
// Wildcard? song.*, match against asset-srcs, make sure it's loaded and return content of first match.
if(src[src.length-1] === "*") {
var needle = src.replace("*", "")
for(var i=0; i < self.src_list.length; i++) {
if(self.src_list[i].indexOf(needle) == 0 && self.data[self.src_list[i]])
return self.data[self.src_list[i]];
}
}
// TODO: self.loaded[src] is false for supported files for some odd reason.
if (self.data[src]) { return self.data[src]; }
else { jaws.log.warn("No such asset: " + src, true); }
}
else {
jaws.log.error("jaws.get: Neither String nor Array. Incorrect URL resource " + src);
return;
}
};
/**
* Returns if specified resource is currently loading or not
* @public
* @param {string} src Resource URL
* @return {boolean|undefined} If resource is currently loading. Otherwise, undefined.
*/
self.isLoading = function(src) {
if (jaws.isString(src)) {
return self.loading[src];
} else {
jaws.log.error("jaws.isLoading: Argument not a String with " + src);
}
};
/**
* Returns if specified resource is loaded or not
* @param src Source URL
* @return {boolean|undefined} If specified resource is loaded or not. Otherwise, undefined.
*/
self.isLoaded = function(src) {
if (jaws.isString(src)) {
return self.loaded[src];
} else {
jaws.log.error("jaws.isLoaded: Argument not a String with " + src);
}
};
/**
* Returns lowercase postfix of specified resource
* @public
* @param {string} src Resource URL
* @returns {string} Lowercase postfix of resource
*/
self.getPostfix = function(src) {
if (jaws.isString(src)) {
return src.toLowerCase().match(/.+\.([^?]+)(\?|$)/)[1];
} else {
jaws.log.error("jaws.assets.getPostfix: Argument not a String with " + src);
}
};
/**
* Determine type of file (Image, Audio, or Video) from its postfix
* @private
* @param {string} src Resource URL
* @returns {string} Matching type {Image, Audio, Video} or the postfix itself
*/
function getType(src) {
if (jaws.isString(src)) {
var postfix = self.getPostfix(src);
return (self.file_type[postfix] ? self.file_type[postfix] : postfix);
} else {
jaws.log.error("jaws.assets.getType: Argument not a String with " + src);
}
}
/**
* Add URL(s) to asset listing for later loading
* @public
* @param {string|array|arguments} src The resource URL(s) to add to the asset listing
* @example
* jaws.assets.add("player.png")
* jaws.assets.add(["media/bullet1.png", "media/bullet2.png"])
* jaws.assets.add("foo.png", "bar.png")
* jaws.assets.loadAll({onload: start_game})
*/
self.add = function(src) {
var list = arguments;
if(list.length == 1 && jaws.isArray(list[0])) list = list[0];
for(var i=0; i < list.length; i++) {
if(jaws.isArray(list[i])) {
self.add(list[i]);
}
else {
if(jaws.isString(list[i])) { self.src_list.push(list[i]) }
else { jaws.log.error("jaws.assets.add: Neither String nor Array. Incorrect URL resource " + src) }
}
}
return self;
};
/**
* Iterate through the list of resource URL(s) and load each in turn.
* @public
* @param {Object} options Object-literal of callback functions
* @config {function} [options.onprogress] The function to be called on progress (when one assets of many is loaded)
* @config {function} [options.onerror] The function to be called if an error occurs
* @config {function} [options.onload] The function to be called when finished
*/
self.loadAll = function(options) {
self.load_count = 0;
self.error_count = 0;
if (options.onprogress && jaws.isFunction(options.onprogress))
self.onprogress = options.onprogress;
if (options.onerror && jaws.isFunction(options.onerror))
self.onerror = options.onerror;
if (options.onload && jaws.isFunction(options.onload))
self.onload = options.onload;
self.src_list.forEach(function(item) {
self.load(item);
});
return self;
};
/**
* Loads a single resource from its given URL
* Will attempt to match a resource to known MIME types.
* If unknown, loads the file as a blob-object.
*
* @public
* @param {string} src Resource URL
* @param {Object} options Object-literal of callback functions
* @config {function} [options.onload] Function to be called when assets has loaded
* @config {function} [options.onerror] Function to be called if an error occurs
* @example
* jaws.load("media/foo.png")
* jaws.load("http://place.tld/foo.png")
*/
self.load = function(src, options) {
if(!options) options = {};
if (!jaws.isString(src)) {
jaws.log.error("jaws.assets.load: Argument not a String with " + src);
return;
}
var asset = {};
var resolved_src = "";
asset.src = src;
asset.onload = options.onload;
asset.onerror = options.onerror;
self.loading[src] = true;
var parser = RegExp('^((f|ht)tp(s)?:)?//');
if (parser.test(src)) {
resolved_src = asset.src;
} else {
resolved_src = self.root + asset.src;
}
if (self.bust_cache) {
resolved_src += "?" + parseInt(Math.random() * 10000000);
}
var type = getType(asset.src);
if (type === "image") {
try {
asset.image = new Image();
asset.image.asset = asset;
asset.image.addEventListener('load', assetLoaded);
asset.image.addEventListener('error', assetError);
asset.image.src = resolved_src;
} catch (e) {
jaws.log.error("Cannot load Image resource " + resolved_src +
" (Message: " + e.message + ", Name: " + e.name + ")");
}
}
else if (self.can_play[self.getPostfix(asset.src)]) {
if (type === "audio") {
try {
asset.audio = new Audio();
asset.audio.asset = asset;
asset.audio.addEventListener('error', assetError);
asset.audio.addEventListener('canplay', assetLoaded); // NOTE: assetLoaded can be called several times during loading.
self.data[asset.src] = asset.audio;
asset.audio.src = resolved_src;
asset.audio.load();
} catch (e) {
jaws.log.error("Cannot load Audio resource " + resolved_src +
" (Message: " + e.message + ", Name: " + e.name + ")");