-
Notifications
You must be signed in to change notification settings - Fork 1
/
jaws.js
4267 lines (3775 loc) · 136 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: Tue Aug 19 2014 00:16:15 GMT+0200 (CEST) */
/**
* @namespace JawsJS core functions.
*
* Jaws, a HTML5 canvas/javascript 2D game development framework
*
* Homepage: http://jawsjs.com/
* Source: http://github.com/ippa/jaws/
* Documentation: http://jawsjs.com/docs/
*
* Works with: Chrome 6.0+, Firefox 3.6+, 4+, IE 9+
* License: LGPL - http://www.gnu.org/licenses/lgpl.html
*
* Jaws uses the "module pattern".
* Adds 1 global, <b>jaws</b>, so plays nice with all other JS libs.
*
* Formating guide:
* jaws.oneFunction()
* jaws.one_variable = 1
* new jaws.OneConstructor
*
* @property {int} mouse_x Mouse X position with respect to the canvas-element
* @property {int} mouse_y Mouse Y position with respect to the canvas-element
* @property {canvas} canvas The detected/created canvas-element used for the game
* @property {context} context The detected/created canvas 2D-context, used for all draw-operations
* @property {int} width Width of the canvas-element
* @property {int} height Height of the canvas-element
*/
var jaws = (function(jaws) {
var title;
var log_tag;
/*
* Placeholders for constructors in extras-dir. We define the constructors here to be able to give ppl better error-msgs.
* When the correct from extras-dir is included, these will be overwritten.
*
*/
//jaws.Parallax = function() { throw("To use jaws.Parallax() you need to include src/extras/parallax.js") }
//jaws.QuadTree = function() { throw("To use QuadTree() you need to include src/extras/quadtree.js") }
//jaws.PixelMap = function() { throw("To use PixelMap() you need to include src/extras/pixel_map.js") }
//jaws.TileMap = function() { throw("To use TileMap() you need to include src/extras/tile_map.js") }
jaws.SpriteList = function() { throw("To use SpriteList() you need to include src/extras/sprite_list.js") }
jaws.Audio = function() { throw("To use jaws.Audio() you need to include src/extras/audio.js") }
/**
* Returns or sets contents of title's innerHTML
* @private
* @param {type} value The new value to set the innerHTML of title
* @returns {string} The innerHTML of title
*/
jaws.title = function(value) {
if (!jaws.isString(value)) {
jaws.log.error("jaws.title: Passed in value is not a String.");
return;
}
if (value) {
return (title.innerHTML = value);
}
return title.innerHTML;
};
/**
* Unpacks Jaws core-constructors into the global namespace.
* If a global property is already taken, a warning will be written to jaws log.
*/
jaws.unpack = function() {
var make_global = ["Sprite", "SpriteList", "Animation", "Viewport", "SpriteSheet", "Parallax", "TileMap", "pressed", "QuadTree"];
make_global.forEach(function(item) {
if (window[item]) {
jaws.log.warn("jaws.unpack: " + item + " already exists in global namespace.");
}
else {
window[item] = jaws[item];
}
});
};
/**
* Writes messages to either log_tag (if set) or console.log (if available)
* @param {string} msg The string to write
* @param {boolean} append If messages should be appended or not
*/
jaws.log = function(msg, append) {
if (!jaws.isString(msg)) {
msg = JSON.stringify(msg);
}
if (jaws.log.on) {
if (log_tag && jaws.log.use_log_element) {
if (append) {
log_tag.innerHTML += msg + "<br />";
}
else {
log_tag.innerHTML = msg;
}
}
if (console.log && jaws.log.use_console) {
console.log("JawsJS: ", msg);
}
}
};
/**
* If logging should take place or not
* @type {boolean}
*/
jaws.log.on = true;
/**
* If console.log should be used during log writing
* @type {boolean}
*/
jaws.log.use_console = false;
/**
* If log_tag should be used during log writing
* @type {boolean}
*/
jaws.log.use_log_element = true;
/**
* Write messages to console.warn (if it exists) or append current log
* @param {string|object} msg String or object to record
* @see jaws.log
*/
jaws.log.warn = function(msg) {
if (console.warn && jaws.log.use_console && jaws.log.on) {
console.warn(msg);
} else {
jaws.log("[WARNING]: " + JSON.stringify(msg), true);
}
};
/**
* Write messages to console.error (if it exists) or append current log
* @param {string|object} msg String or object to record
* @see jaws.log
*/
jaws.log.error = function(msg) {
if (console.error && jaws.log.use_console && jaws.log.on) {
console.error(msg);
} else {
jaws.log("[ERROR]: " + JSON.stringify(msg), true);
}
};
/**
* Write messages to console.info (if it exists) or append current log
* @param {string|object} msg String or object to record
* @see jaws.log
*/
jaws.log.info = function(msg) {
if (console.info && jaws.log.use_console && jaws.log.on) {
console.info(msg);
} else {
jaws.log("[INFO]: " + JSON.stringify(msg), true);
}
};
/**
* Write messages to console.debug (if it exists) or append current log
* @param {string|object} msg String or object to record
* @see jaws.log
*/
jaws.log.debug = function(msg) {
if (console.debug && jaws.log.use_console && jaws.log.on) {
console.debug(msg);
} else {
jaws.log("[DEBUG]: " + JSON.stringify(msg), true);
}
};
/**
* Clears the contents of log_tag element (if set) and console.log (if set)
*/
jaws.log.clear = function() {
if (log_tag) {
log_tag.innerHTML = "";
}
if (console.clear) {
console.clear();
}
};
/**
* Initalizes jaws{canvas, context, dom, width, height}
* @private
* @param {object} options Object-literal of constructor properties
* @see jaws.url_parameters()
*/
jaws.init = function(options) {
/* Find <title> tag */
title = document.getElementsByTagName('title')[0];
jaws.url_parameters = jaws.getUrlParameters();
jaws.canvas = document.getElementsByTagName('canvas')[0];
if (!jaws.canvas) {
jaws.dom = document.getElementById("canvas");
}
// Ordinary <canvas>, get context
if (jaws.canvas) {
jaws.context = jaws.canvas.getContext('2d');
}
else if (jaws.dom) {
jaws.dom.style.position = "relative";
}
else {
jaws.canvas = document.createElement("canvas");
jaws.canvas.width = options.width;
jaws.canvas.height = options.height;
jaws.context = jaws.canvas.getContext('2d');
document.body.appendChild(jaws.canvas);
}
/*
* If debug=1 parameter is present in the URL, let's either find <div id="jaws-log"> or create the tag.
* jaws.log(message) will use this div for debug/info output to the gamer or developer
*
*/
log_tag = document.getElementById('jaws-log');
if (jaws.url_parameters["debug"]) {
if (!log_tag) {
log_tag = document.createElement("div");
log_tag.id = "jaws-log";
log_tag.style.cssText = "overflow: auto; color: #aaaaaa; width: 300px; height: 150px; margin: 40px auto 0px auto; padding: 5px; border: #444444 1px solid; clear: both; font: 10px verdana; text-align: left;";
document.body.appendChild(log_tag);
}
}
if(jaws.url_parameters["bust_cache"]) {
jaws.log.info("Busting cache when loading assets")
jaws.assets.bust_cache = true;
}
/* Let's scale sprites retro-style by default */
if (jaws.context)
jaws.useCrispScaling();
jaws.width = jaws.canvas ? jaws.canvas.width : jaws.dom.offsetWidth;
jaws.height = jaws.canvas ? jaws.canvas.height : jaws.dom.offsetHeight;
jaws.mouse_x = 0;
jaws.mouse_y = 0;
window.addEventListener("mousemove", saveMousePosition);
};
/**
* Use 'retro' crisp scaling when drawing sprites through the canvas API, this is the default
*/
jaws.useCrispScaling = function() {
jaws.context.imageSmoothingEnabled = false;
jaws.context.webkitImageSmoothingEnabled = false;
jaws.context.mozImageSmoothingEnabled = false;
};
/**
* Use smooth antialiased scaling when drawing sprites through the canvas API
*/
jaws.useSmoothScaling = function() {
jaws.context.imageSmoothingEnabled = true;
jaws.context.webkitImageSmoothingEnabled = true;
jaws.context.mozImageSmoothingEnabled = true;
};
/**
* Keeps updated mouse coordinates in jaws.mouse_x and jaws.mouse_y
* This is called each time event "mousemove" triggers.
* @private
* @param {EventObject} e The EventObject populated by the calling event
*/
function saveMousePosition(e) {
jaws.mouse_x = (e.pageX || e.clientX);
jaws.mouse_y = (e.pageY || e.clientY);
var game_area = jaws.canvas ? jaws.canvas : jaws.dom;
jaws.mouse_x -= game_area.offsetLeft;
jaws.mouse_y -= game_area.offsetTop;
}
/**
* 1) Calls jaws.init(), detects or creats a canvas, and sets up the 2D context (jaws.canvas and jaws.context).
* 2) Pre-loads all defined assets with jaws.assets.loadAll().
* 3) Creates an instance of game_state and calls setup() on that instance.
* 4) Loops calls to update() and draw() with given FPS until game ends or another game state is activated.
* @param {function} game_state The game state function to be started
* @param {object} options Object-literal of game loop properties
* @param {object} game_state_setup_options Object-literal of game state properties and values
* @see jaws.init()
* @see jaws.setupInput()
* @see jaws.assets.loadAll()
* @see jaws.switchGameState()
* @example
*
* jaws.start(MyGame) // Start game state Game() with default options
* jaws.start(MyGame, {fps: 30}) // Start game state Game() with options, in this case jaws will run your game with 30 frames per second.
* jaws.start(window) // Use global functions setup(), update() and draw() if available. Not the recommended way but useful for testing and mini-games.
*
*/
jaws.start = function(game_state, options, game_state_setup_options) {
if (!options) options = {};
var fps = options.fps || 60;
if (options.loading_screen === undefined) options.loading_screen = true;
if (!options.width) options.width = 500;
if (!options.height) options.height = 300;
/* Takes care of finding/creating canvas-element and debug-div */
jaws.init(options);
if (!jaws.isFunction(game_state) && !jaws.isObject(game_state)) {
jaws.log.error("jaws.start: Passed in GameState is niether function or object");
return;
}
if (!jaws.isObject(game_state_setup_options) && game_state_setup_options !== undefined) {
jaws.log.error("jaws.start: The setup options for the game state is not an object.");
return;
}
if (options.loading_screen) {
jaws.assets.displayProgress(0);
}
jaws.log.info("setupInput()", true);
jaws.setupInput();
/* Callback for when one single asset has been loaded */
function assetProgress(src, percent_done) {
jaws.log.info(percent_done + "%: " + src, true);
if (options.loading_screen) {
jaws.assets.displayProgress(percent_done);
}
}
/* Callback for when an asset can't be loaded*/
function assetError(src, percent_done) {
jaws.log.info(percent_done + "%: Error loading asset " + src, true);
}
/* Callback for when all assets are loaded */
function assetsLoaded() {
jaws.log.info("all assets loaded", true);
jaws.switchGameState(game_state || window, {fps: fps}, game_state_setup_options);
}
jaws.log.info("assets.loadAll()", true);
if (jaws.assets.length() > 0) {
jaws.assets.loadAll({onprogress: assetProgress, onerror: assetError, onload: assetsLoaded});
}
else {
assetsLoaded();
}
};
/**
* Switchs to a new active game state and saves previous game state in jaws.previous_game_state
* @param {function} game_state The game state function to start
* @param {object} options The object-literal properties to pass to the new game loop
* @param {object} game_state_setup_options The object-literal properties to pass to starting game state
* @example
*
* function MenuState() {
* this.setup = function() { ... }
* this.draw = function() { ... }
* this.update = function() {
* if(pressed("enter")) jaws.switchGameState(GameState); // Start game when Enter is pressed
* }
* }
*
* function GameState() {
* this.setup = function() { ... }
* this.update = function() { ... }
* this.draw = function() { ... }
* }
*
* jaws.start(MenuState)
*
*/
jaws.switchGameState = function(game_state, options, game_state_setup_options) {
if(options === undefined) options = {};
if(jaws.isFunction(game_state)) {
game_state = new game_state;
}
if(!jaws.isObject(game_state)) {
jaws.log.error("jaws.switchGameState: Passed in GameState should be a Function or an Object.");
return;
}
var fps = (options && options.fps) || (jaws.game_loop && jaws.game_loop.fps) || 60;
var setup = options.setup
jaws.game_loop && jaws.game_loop.stop();
jaws.clearKeyCallbacks();
jaws.previous_game_state = jaws.game_state;
jaws.game_state = game_state;
jaws.game_loop = new jaws.GameLoop(game_state, {fps: fps, setup: setup}, game_state_setup_options);
jaws.game_loop.start();
};
/**
* Creates a new HTMLCanvasElement from a HTMLImageElement
* @param {HTMLImageElement} image The HTMLImageElement to convert to a HTMLCanvasElement
* @returns {HTMLCanvasElement} A HTMLCanvasElement with drawn HTMLImageElement content
*/
jaws.imageToCanvas = function(image) {
if (jaws.isCanvas(image)) return image;
if (!jaws.isImage(image)) {
jaws.log.error("jaws.imageToCanvas: Passed in object is not an Image.");
return;
}
var canvas = document.createElement("canvas");
canvas.src = image.src;
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height);
return canvas;
};
/**
* Returns object as an array
* @param {object} obj An array or object
* @returns {array} Either an array or the object as an array
* @example
*
* jaws.forceArray(1) // --> [1]
* jaws.forceArray([1,2]) // --> [1,2]
*/
jaws.forceArray = function(obj) {
return Array.isArray(obj) ? obj : [obj];
};
/**
* Clears screen (the canvas-element) through context.clearRect()
*/
jaws.clear = function() {
jaws.context.clearRect(0, 0, jaws.width, jaws.height);
};
/** Fills the screen with given fill_style */
jaws.fill = function(fill_style) {
jaws.context.fillStyle = fill_style;
jaws.context.fillRect(0, 0, jaws.width, jaws.height);
};
/**
* calls draw() on everything you throw on it. Give it arrays, argumentlists, arrays of arrays.
*
*/
jaws.draw = function() {
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])) jaws.draw(list[i]);
else if(list[i].draw) list[i].draw();
}
}
/**
* calls update() on everything you throw on it. Give it arrays, argumentlists, arrays of arrays.
*
*/
jaws.update = function() {
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])) jaws.update(list[i]);
else if(list[i].update) list[i].update();
}
}
/**
* Tests if object is an image or not
* @param {object} obj An Image or image-like object
* @returns {boolean} If object's prototype is "HTMLImageElement"
*/
jaws.isImage = function(obj) {
return Object.prototype.toString.call(obj) === "[object HTMLImageElement]";
};
/**
* Tests if object is a Canvas object
* @param {type} obj A canvas or canvas-like object
* @returns {boolean} If object's prototype is "HTMLCanvasElement"
*/
jaws.isCanvas = function(obj) {
return Object.prototype.toString.call(obj) === "[object HTMLCanvasElement]";
};
/**
* Tests if an object is either a canvas or an image object
* @param {object} obj A canvas or canva-like object
* @returns {boolean} If object isImage or isCanvas
*/
jaws.isDrawable = function(obj) {
return jaws.isImage(obj) || jaws.isCanvas(obj);
};
/**
* Tests if an object is a string or not
* @param {object} obj A string or string-like object
* @returns {boolean} The result of typeof and constructor testing
*/
jaws.isString = function(obj) {
return typeof obj === "string" || (typeof obj === "object" && obj.constructor === String);
};
/**
* Tests if an object is a number or not
* @param {number} n A number or number-like value
* @returns {boolean} If n passed isNaN() and isFinite()
*/
jaws.isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
/**
* Tests if an object is an Array or not
* @param {object} obj An array or array-like object
* @returns {boolean} If object's constructor is "Array"
*/
jaws.isArray = function(obj) {
if (!obj)
return false;
return !(obj.constructor.toString().indexOf("Array") === -1);
};
/**
* Tests if an object is an Object or not
* @param {object} value An object or object-like enitity
* @returns {boolean} If object is not null and typeof 'object'
*/
jaws.isObject = function(value) {
return value !== null && typeof value === 'object';
};
/**
* Tests if an object is a function or not
* @param {object} obj A function or function-like object
* @returns {boolean} If the prototype of the object is "Function"
*/
jaws.isFunction = function(obj) {
return (Object.prototype.toString.call(obj) === "[object Function]");
};
/**
* Tests if an object is a regular expression or not
* @param {object} obj A /regexp/-object
* @returns {boolean} If the object is an instance of RegExp
*/
jaws.isRegExp = function(obj) {
return (obj instanceof RegExp);
};
/**
* Tests if an object is within drawing canvas (jaws.width and jaws.height)
* @param {object} item An object with both x and y properties
* @returns {boolean} If the item's x and y are less than 0 or more than jaws.width or jaws.height
*/
jaws.isOutsideCanvas = function(item) {
if (item.x && item.y) {
return (item.x < 0 || item.y < 0 || item.x > jaws.width || item.y > jaws.height);
}
};
/**
* Sets x and y properties to 0 (if less than), or jaws.width or jaws.height (if greater than)
* @param {object} item An object with x and y properties
*/
jaws.forceInsideCanvas = function(item) {
if (item.x && item.y) {
if (item.x < 0) {
item.x = 0;
}
if (item.x > jaws.width) {
item.x = jaws.width;
}
if (item.y < 0) {
item.y = 0;
}
if (item.y > jaws.height) {
item.y = jaws.height;
}
}
};
/**
* Parses current window.location for URL parameters and values
* @returns {array} Hash of url-parameters and their values
* @example
* // Given the current URL is <b>http://test.com/?debug=1&foo=bar</b>
* jaws.getUrlParameters() // --> {debug: 1, foo: bar}
*/
jaws.getUrlParameters = function() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
};
/**
* Compares an object's default properties against those sent to its constructor
* @param {object} object The object to compare and assign new values
* @param {object} options Object-literal of constructor properties and new values
* @param {object} defaults Object-literal of properties and their default values
*/
jaws.parseOptions = function(object, options, defaults) {
object["options"] = options;
for (var option in options) {
if (defaults[option] === undefined) {
jaws.log.warn("jaws.parseOptions: Unsupported property " + option + "for " + object.constructor);
}
}
for (var option in defaults) {
if( jaws.isFunction(defaults[option]) ) defaults[option] = defaults[option]();
object[option] = (options[option] !== undefined) ? options[option] : jaws.clone(defaults[option]);
}
};
/**
* Returns a shallow copy of an array or object
* @param {array|object} value The array or object to clone
* @returns {array|object} A copy of an array of object
*/
jaws.clone = function(value) {
if (jaws.isArray(value))
return value.slice(0);
if (jaws.isObject(value))
return JSON.parse(JSON.stringify(value));
return value;
};
/*
* Converts image to canvas 2D context. Then you can draw on it :).
*/
jaws.imageToCanvasContext = function(image) {
var canvas = document.createElement("canvas")
canvas.width = image.width
canvas.height = image.height
var context = canvas.getContext("2d")
if(jaws.context) {
context.imageSmoothingEnabled = jaws.context.mozImageSmoothingEnabled;
context.webkitImageSmoothingEnabled = jaws.context.mozImageSmoothingEnabled;
context.mozImageSmoothingEnabled = jaws.context.mozImageSmoothingEnabled;
}
context.drawImage(image, 0, 0, canvas.width, canvas.height)
return context
}
/**
* scale 'image' by factor 'factor'.
* Scaling is done using nearest-neighbor ( retro-blocky-style ).
* Returns a canvas.
*/
jaws.retroScaleImage = function(image, factor) {
var canvas = jaws.isImage(image) ? jaws.imageToCanvas(image) : image
var context = canvas.getContext("2d")
var data = context.getImageData(0,0,canvas.width,canvas.height).data
// Create new canvas to return
var canvas2 = document.createElement("canvas")
canvas2.width = image.width * factor
canvas2.height = image.height * factor
var context2 = canvas2.getContext("2d")
var to_data = context2.createImageData(canvas2.width, canvas2.height)
var w2 = to_data.width
var h2 = to_data.height
for (var y=0; y < h2; y += 1) {
var y2 = Math.floor(y / factor)
var y_as_x = y * to_data.width
var y2_as_x = y2 * image.width
for (var x=0; x < w2; x += 1) {
var x2 = Math.floor(x / factor)
var y_dst = (y_as_x + x) * 4
var y_src = (y2_as_x + x2) * 4
to_data.data[y_dst] = data[y_src];
to_data.data[y_dst+1] = data[y_src+1];
to_data.data[y_dst+2] = data[y_src+2];
to_data.data[y_dst+3] = data[y_src+3];
}
}
context2.putImageData(to_data, 0, 0)
return canvas2
}
return jaws;
})(jaws || {});
// Support CommonJS require()
if(typeof module !== "undefined" && ('exports' in module)) { module.exports = jaws }
var jaws = (function(jaws) {
var pressed_keys = {}
var previously_pressed_keys = {}
var keycode_to_string = []
var on_keydown_callbacks = []
var on_keyup_callbacks = []
var mousebuttoncode_to_string = []
var ie_mousebuttoncode_to_string = []
/** @private
* Map all javascript keycodes to easy-to-remember letters/words
*/
jaws.setupInput = function() {
var k = []
k[8] = "backspace"
k[9] = "tab"
k[13] = "enter"
k[16] = "shift"
k[17] = "ctrl"
k[18] = "alt"
k[19] = "pause"
k[20] = "capslock"
k[27] = "esc"
k[32] = "space"
k[33] = "pageup"
k[34] = "pagedown"
k[35] = "end"
k[36] = "home"
k[37] = "left"
k[38] = "up"
k[39] = "right"
k[40] = "down"
k[45] = "insert"
k[46] = "delete"
k[91] = "left_window_key leftwindowkey"
k[92] = "right_window_key rightwindowkey"
k[93] = "select_key selectkey"
k[106] = "multiply *"
k[107] = "add plus +"
k[109] = "subtract minus -"
k[110] = "decimalpoint"
k[111] = "divide /"
k[144] = "numlock"
k[145] = "scrollock"
k[186] = "semicolon ;"
k[187] = "equalsign ="
k[188] = "comma ,"
k[189] = "dash -"
k[190] = "period ."
k[191] = "forwardslash /"
k[192] = "graveaccent `"
k[219] = "openbracket ["
k[220] = "backslash \\"
k[221] = "closebracket ]"
k[222] = "singlequote '"
var m = []
m[0] = "left_mouse_button"
m[1] = "center_mouse_button"
m[2] = "right_mouse_button"
var ie_m = [];
ie_m[1] = "left_mouse_button";
ie_m[2] = "right_mouse_button";
ie_m[4] = "center_mouse_button";
mousebuttoncode_to_string = m
ie_mousebuttoncode_to_string = ie_m;
var numpadkeys = ["numpad0","numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9"]
var fkeys = ["f1","f2","f3","f4","f5","f6","f7","f8","f9"]
var numbers = ["0","1","2","3","4","5","6","7","8","9"]
var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for(var i = 0; numbers[i]; i++) { k[48+i] = numbers[i] }
for(var i = 0; letters[i]; i++) { k[65+i] = letters[i] }
for(var i = 0; numpadkeys[i]; i++) { k[96+i] = numpadkeys[i] }
for(var i = 0; fkeys[i]; i++) { k[112+i] = fkeys[i] }
keycode_to_string = k
window.addEventListener("keydown", handleKeyDown)
window.addEventListener("keyup", handleKeyUp)
var jawswindow = jaws.canvas || jaws.dom
jawswindow.addEventListener("mousedown", handleMouseDown, false);
jawswindow.addEventListener("mouseup", handleMouseUp, false);
jawswindow.addEventListener("touchstart", handleTouchStart, false);
jawswindow.addEventListener("touchend", handleTouchEnd, false);
window.addEventListener("blur", resetPressedKeys, false);
// this turns off the right click context menu which screws up the mouseup event for button 2
document.oncontextmenu = function() {return false};
}
/** @private
* Reset input-hash. Called when game is blurred so a key-controlled player doesn't keep on moving when the game isn't focused.
*/
function resetPressedKeys(e) {
pressed_keys = {};
}
/** @private
* handle event "onkeydown" by remembering what key was pressed
*/
function handleKeyUp(e) {
event = (e) ? e : window.event
var human_names = keycode_to_string[event.keyCode].split(" ")
human_names.forEach( function(human_name) {
pressed_keys[human_name] = false
if(on_keyup_callbacks[human_name]) {
on_keyup_callbacks[human_name](human_name)
e.preventDefault()
}
if(prevent_default_keys[human_name]) { e.preventDefault() }
});
}
/** @private
* handle event "onkeydown" by remembering what key was un-pressed
*/
function handleKeyDown(e) {
event = (e) ? e : window.event
var human_names = keycode_to_string[event.keyCode].split(" ")
human_names.forEach( function(human_name) {
pressed_keys[human_name] = true
if(on_keydown_callbacks[human_name]) {
on_keydown_callbacks[human_name](human_name)
e.preventDefault()
}
if(prevent_default_keys[human_name]) { e.preventDefault() }
});
}
/** @private
* handle event "onmousedown" by remembering what button was pressed
*/
function handleMouseDown(e) {
event = (e) ? e : window.event
var human_name = mousebuttoncode_to_string[event.button] // 0 1 2
if (navigator.appName == "Microsoft Internet Explorer"){
human_name = ie_mousebuttoncode_to_string[event.button];
}
pressed_keys[human_name] = true
if(on_keydown_callbacks[human_name]) {
on_keydown_callbacks[human_name](human_name)
e.preventDefault()
}
}
/** @private
* handle event "onmouseup" by remembering what button was un-pressed
*/
function handleMouseUp(e) {
event = (e) ? e : window.event
var human_name = mousebuttoncode_to_string[event.button]
if (navigator.appName == "Microsoft Internet Explorer"){
human_name = ie_mousebuttoncode_to_string[event.button];
}
pressed_keys[human_name] = false
if(on_keyup_callbacks[human_name]) {
on_keyup_callbacks[human_name](human_name)
e.preventDefault()
}
}
/** @private
* handle event "touchstart" by remembering what button was pressed
*/
function handleTouchStart(e) {
event = (e) ? e : window.event
pressed_keys["left_mouse_button"] = true
jaws.mouse_x = e.touches[0].pageX - jaws.canvas.offsetLeft;
jaws.mouse_y = e.touches[0].pageY - jaws.canvas.offsetTop;
//e.preventDefault()
}
/** @private
* handle event "touchend" by remembering what button was pressed
*/
function handleTouchEnd(e) {
event = (e) ? e : window.event
pressed_keys["left_mouse_button"] = false
jaws.mouse_x = undefined;
jaws.mouse_y = undefined;
}
var prevent_default_keys = []
/**
* Prevents default browseraction for given keys.
* @example
* jaws.preventDefaultKeys( ["down"] ) // Stop down-arrow-key from scrolling page down
*/
jaws.preventDefaultKeys = function(array_of_strings) {
var list = arguments;
if(list.length == 1 && jaws.isArray(list[0])) list = list[0];
for(var i=0; i < list.length; i++) {
prevent_default_keys[list[i]] = true;
}
}
/**
* Check if *keys* are pressed. Second argument specifies use of logical AND when checking multiple keys.
* @example
* jaws.pressed("left a"); // returns true if left arrow key OR a is pressed
* jaws.pressed("ctrl c", true); // returns true if ctrl AND a is pressed
*/
jaws.pressed = function(keys, logical_and) {
if(jaws.isString(keys)) { keys = keys.split(" ") }
if(logical_and) { return keys.every( function(key) { return pressed_keys[key] } ) }
else { return keys.some( function(key) { return pressed_keys[key] } ) }
}
/**
* Check if *keys* are pressed, but only return true Once for any given keys. Once keys have been released, pressedWithoutRepeat can return true again when keys are pressed.
* Second argument specifies use of logical AND when checking multiple keys.
* @example
* if(jaws.pressedWithoutRepeat("space")) { player.jump() } // with this in the gameloop player will only jump once even if space is held down
*/
jaws.pressedWithoutRepeat = function(keys, logical_and) {
if( jaws.pressed(keys, logical_and) ) {
if(!previously_pressed_keys[keys]) {
previously_pressed_keys[keys] = true
return true
}
}
else {
previously_pressed_keys[keys] = false
return false
}
}
/**
* sets up a callback for a key (or array of keys) to call when it's pressed down
*
* @example
* // call goLeft() when left arrow key is pressed
* jaws.on_keypress("left", goLeft)
*
* // call fireWeapon() when SPACE or CTRL is pressed
* jaws.on_keypress(["space","ctrl"], fireWeapon)
*/
jaws.on_keydown = function(key, callback) {
if(jaws.isArray(key)) {
for(var i=0; key[i]; i++) {
on_keydown_callbacks[key[i]] = callback
}
}
else {
on_keydown_callbacks[key] = callback
}
}
/**
* sets up a callback when a key (or array of keys) to call when it's released
*/
jaws.on_keyup = function(key, callback) {
if(jaws.isArray(key)) {
for(var i=0; key[i]; i++) {
on_keyup_callbacks[key[i]] = callback
}
}
else {
on_keyup_callbacks[key] = callback
}
}
/** @private
* Clean up all callbacks set by on_keydown / on_keyup
*/
jaws.clearKeyCallbacks = function() {
on_keyup_callbacks = []
on_keydown_callbacks = []
}