-
-
Notifications
You must be signed in to change notification settings - Fork 97
/
kontra.mjs
3871 lines (3454 loc) · 106 KB
/
kontra.mjs
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
/**
* A simple event system. Allows you to hook into Kontra lifecycle events or create your own, such as for [Plugins](api/plugin).
*
* ```js
* import { on, off, emit } from 'kontra';
*
* function callback(a, b, c) {
* console.log({a, b, c});
* });
*
* on('myEvent', callback);
* emit('myEvent', 1, 2, 3); //=> {a: 1, b: 2, c: 3}
* off('myEvent', callback);
* ```
* @sectionName Events
*/
// expose for testing
let callbacks = {};
/**
* There are currently only three lifecycle events:
* - `init` - Emitted after `konta.init()` is called.
* - `tick` - Emitted every frame of kontra.GameLoop before the loops `update()` and `render()` functions are called.
* - `assetLoaded` - Emitted after an asset has fully loaded using the asset loader. The callback function is passed the asset and the url of the asset as parameters.
* @sectionName Lifecycle Events
*/
/**
* Register a callback for an event to be called whenever the event is emitted. The callback will be passed all arguments used in the `emit` call.
* @function on
*
* @param {String} event - Name of the event.
* @param {Function} callback - Function that will be called when the event is emitted.
*/
function on(event, callback) {
callbacks[event] = callbacks[event] || [];
callbacks[event].push(callback);
}
/**
* Remove a callback for an event.
* @function off
*
* @param {String} event - Name of the event.
* @param {Function} callback - The function that was passed during registration.
*/
function off(event, callback) {
let index;
if (!callbacks[event] || (index = callbacks[event].indexOf(callback)) < 0) return;
callbacks[event].splice(index, 1);
}
/**
* Call all callback functions for the event. All arguments will be passed to the callback functions.
* @function emit
*
* @param {String} event - Name of the event.
* @param {*} [args] - Arguments passed to all callbacks.
*/
function emit(event, ...args) {
if (!callbacks[event]) return;
callbacks[event].map(fn => fn(...args));
}
/**
* Functions for initializing the Kontra library and getting the canvas and context
* objects.
*
* ```js
* import { getCanvas, getContext, init } from 'kontra';
*
* let { canvas, context } = init();
*
* // or can get canvas and context through functions
* canvas = getCanvas();
* context = getContext();
* ```
* @sectionName Core
*/
let canvasEl;
let context;
/**
* Return the canvas element.
* @function getCanvas
*
* @returns {HTMLCanvasElement} The canvas element for the game.
*/
function getCanvas() {
return canvasEl;
}
/**
* Return the context object.
* @function getContext
*
* @returns {CanvasRenderingContext2D} The context object the game draws to.
*/
function getContext() {
return context;
}
/**
* Initialize the library and set up the canvas. Typically you will call `init()` as the first thing and give it the canvas to use. This will allow all Kontra objects to reference the canvas when created.
*
* ```js
* import { init } from 'kontra';
*
* let { canvas, context } = init('game');
* ```
* @function init
*
* @param {String|HTMLCanvasElement} [canvas] - The canvas for Kontra to use. Can either be the ID of the canvas element or the canvas element itself. Defaults to using the first canvas element on the page.
*
* @returns {Object} An object with properties `canvas` and `context`. `canvas` it the canvas element for the game and `context` is the context object the game draws to.
*/
function init(canvas) {
// check if canvas is a string first, an element next, or default to getting
// first canvas on page
canvasEl = document.getElementById(canvas) ||
canvas ||
document.querySelector('canvas');
// @if DEBUG
if (!canvasEl) {
throw Error('You must provide a canvas element for the game');
}
// @endif
context = canvasEl.getContext('2d');
context.imageSmoothingEnabled = false;
emit('init');
return { canvas: canvasEl, context };
}
/**
* An object for drawing sprite sheet animations.
*
* An animation defines the sequence of frames to use from a sprite sheet. It also defines at what speed the animation should run using `frameRate`.
*
* Typically you don't create an kontra.Animation directly, but rather you would create them from kontra.SpriteSheet by passing the `animations` argument.
*
* ```js
* import { SpriteSheet, Animation } from 'kontra';
*
* let image = new Image();
* image.src = 'assets/imgs/character_walk_sheet.png';
* image.onload = function() {
* let spriteSheet = SpriteSheet({
* image: image,
* frameWidth: 72,
* frameHeight: 97
* });
*
* // you typically wouldn't create an Animation this way
* let animation = Animation({
* spriteSheet: spriteSheet,
* frames: [1,2,3,6],
* frameRate: 30
* });
* };
* ```
* @class Animation
*
* @param {Object} properties - Properties of the animation.
* @param {kontra.SpriteSheet} properties.spriteSheet - Sprite sheet for the animation.
* @param {Number[]} properties.frames - List of frames of the animation.
* @param {Number} properties.frameRate - Number of frames to display in one second.
* @param {Boolean} [properties.loop=true] - If the animation should loop.
*/
class Animation {
constructor({spriteSheet, frames, frameRate, loop = true} = {}) {
/**
* The sprite sheet to use for the animation.
* @memberof Animation
* @property {kontra.SpriteSheet} spriteSheet
*/
this.spriteSheet = spriteSheet;
/**
* Sequence of frames to use from the sprite sheet.
* @memberof Animation
* @property {Number[]} frames
*/
this.frames = frames;
/**
* Number of frames to display per second. Adjusting this value will change the speed of the animation.
* @memberof Animation
* @property {Number} frameRate
*/
this.frameRate = frameRate;
/**
* If the animation should loop back to the beginning once completed.
* @memberof Animation
* @property {Boolean} loop
*/
this.loop = loop;
let { width, height, margin = 0 } = spriteSheet.frame;
/**
* The width of an individual frame. Taken from the property of the same name in the [spriteSheet](api/animation/#spriteSheet).
* @memberof Animation
* @property {Number} width
*/
this.width = width;
/**
* The height of an individual frame. Taken from the property of the same name in the [spriteSheet](api/animation/#spriteSheet).
* @memberof Animation
* @property {Number} height
*/
this.height = height;
/**
* The space between each frame. Taken from the property of the same name in the [spriteSheet](api/animation/#spriteSheet).
* @memberof Animation
* @property {Number} margin
*/
this.margin = margin;
// f = frame, a = accumulator
this._f = 0;
this._a = 0;
}
/**
* Clone an animation so it can be used more than once. By default animations passed to kontra.Sprite will be cloned so no two sprites update the same animation. Otherwise two sprites who shared the same animation would make it update twice as fast.
* @memberof Animation
* @function clone
*
* @returns {kontra.Animation} A new kontra.Animation instance.
*/
clone() {
return animationFactory(this);
}
/**
* Reset an animation to the first frame.
* @memberof Animation
* @function reset
*/
reset() {
this._f = 0;
this._a = 0;
}
/**
* Update the animation.
* @memberof Animation
* @function update
*
* @param {Number} [dt=1/60] - Time since last update.
*/
update(dt = 1/60) {
// if the animation doesn't loop we stop at the last frame
if (!this.loop && this._f == this.frames.length-1) return;
this._a += dt;
// update to the next frame if it's time
while (this._a * this.frameRate >= 1) {
this._f = ++this._f % this.frames.length;
this._a -= 1 / this.frameRate;
}
}
/**
* Draw the current frame of the animation.
* @memberof Animation
* @function render
*
* @param {Object} properties - Properties to draw the animation.
* @param {Number} properties.x - X position to draw the animation.
* @param {Number} properties.y - Y position to draw the animation.
* @param {Number} [properties.width] - width of the sprite. Defaults to [Animation.width](api/animation#width).
* @param {Number} [properties.height] - height of the sprite. Defaults to [Animation.height](api/animation#height).
* @param {CanvasRenderingContext2D} [properties.context] - The context the animation should draw to. Defaults to [core.getContext()](api/core#getContext).
*/
render({x, y, width = this.width, height = this.height, context = getContext()} = {}) {
// get the row and col of the frame
let row = this.frames[this._f] / this.spriteSheet._f | 0;
let col = this.frames[this._f] % this.spriteSheet._f | 0;
context.drawImage(
this.spriteSheet.image,
col * this.width + (col * 2 + 1) * this.margin,
row * this.height + (row * 2 + 1) * this.margin,
this.width, this.height,
x, y,
width, height
);
}
}
function animationFactory(properties) {
return new Animation(properties);
}
animationFactory.prototype = Animation.prototype;
animationFactory.class = Animation;
/**
* A promise based asset loader for loading images, audio, and data files. An `assetLoaded` event is emitted after each asset is fully loaded. The callback for the event is passed the asset and the url to the asset as parameters.
*
* ```js
* import { load, on } from 'kontra';
*
* let numAssets = 3;
* let assetsLoaded = 0;
* on('assetLoaded', (asset, url) => {
* assetsLoaded++;
*
* // inform user or update progress bar
* });
*
* load(
* 'assets/imgs/character.png',
* 'assets/data/tile_engine_basic.json',
* ['/audio/music.ogg', '/audio/music.mp3']
* ).then(function(assets) {
* // all assets have loaded
* }).catch(function(err) {
* // error loading an asset
* });
* ```
* @sectionName Assets
*/
let imageRegex = /(jpeg|jpg|gif|png)$/;
let audioRegex = /(wav|mp3|ogg|aac)$/;
let leadingSlash = /^\//;
let trailingSlash = /\/$/;
let dataMap = new WeakMap();
let imagePath = '';
let audioPath = '';
let dataPath = '';
/**
* Get the full URL from the base.
*
* @param {String} url - The URL to the asset.
* @param {String} base - Base URL.
*
* @returns {String}
*/
function getUrl(url, base) {
return new URL(url, base).href;
}
/**
* Join a base path and asset path.
*
* @param {String} base - The asset base path.
* @param {String} url - The URL to the asset.
*
* @returns {String}
*/
function joinPath(base, url) {
return [base.replace(trailingSlash, ''), base ? url.replace(leadingSlash, '') : url]
.filter(s => s)
.join('/')
}
/**
* Get the extension of an asset.
*
* @param {String} url - The URL to the asset.
*
* @returns {String}
*/
function getExtension(url) {
return url.split('.').pop();
}
/**
* Get the name of an asset.
*
* @param {String} url - The URL to the asset.
*
* @returns {String}
*/
function getName(url) {
let name = url.replace('.' + getExtension(url), '');
// remove leading slash if there is no folder in the path
// @see https://stackoverflow.com/a/50592629/2124254
return name.split('/').length == 2 ? name.replace(leadingSlash, '') : name;
}
/**
* Get browser audio playability.
* @see https://github.com/Modernizr/Modernizr/blob/master/feature-detects/audio.js
*
* @param {HTMLMediaElement} audio - Audio element.
*
* @returns {object}
*/
function getCanPlay(audio) {
return {
wav: '',
mp3: audio.canPlayType('audio/mpeg;'),
ogg: audio.canPlayType('audio/ogg; codecs="vorbis"'),
aac: audio.canPlayType('audio/aac;')
};
}
/**
* Object of all loaded image assets by both file name and path. If the base [image path](api/assets/#setImagePath) was set before the image was loaded, the file name and path will not include the base image path.
*
* ```js
* import { load, setImagePath, imageAssets } from 'kontra';
*
* load('assets/imgs/character.png').then(function() {
* // Image asset can be accessed by both
* // name: imageAssets['assets/imgs/character']
* // path: imageAssets['assets/imgs/character.png']
* });
*
* setImagePath('assets/imgs');
* load('character_walk_sheet.png').then(function() {
* // Image asset can be accessed by both
* // name: imageAssets['character_walk_sheet']
* // path: imageAssets['character_walk_sheet.png']
* });
* ```
* @property {Object} imageAssets
*/
let imageAssets = {};
/**
* Object of all loaded audio assets by both file name and path. If the base [audio path](api/assets/#setAudioPath) was set before the audio was loaded, the file name and path will not include the base audio path.
*
* ```js
* import { load, setAudioPath, audioAssets } from 'kontra';
*
* load('/audio/music.ogg').then(function() {
* // Audio asset can be accessed by both
* // name: audioAssets['/audio/music']
* // path: audioAssets['/audio/music.ogg']
* });
*
* setAudioPath('/audio');
* load('sound.ogg').then(function() {
* // Audio asset can be accessed by both
* // name: audioAssets['sound']
* // path: audioAssets['sound.ogg']
* });
* ```
* @property {Object} audioAssets
*/
let audioAssets = {};
/**
* Object of all loaded data assets by both file name and path. If the base [data path](api/assets/#setDataPath) was set before the data was loaded, the file name and path will not include the base data path.
*
* ```js
* import { load, setDataPath, dataAssets } from 'kontra';
*
* load('assets/data/file.txt').then(function() {
* // Audio asset can be accessed by both
* // name: dataAssets['assets/data/file']
* // path: dataAssets['assets/data/file.txt']
* });
*
* setDataPath('assets/data');
* load('info.json').then(function() {
* // Audio asset can be accessed by both
* // name: dataAssets['info']
* // path: dataAssets['info.json']
* });
* ```
* @property {Object} dataAssets
*/
let dataAssets = {};
/**
* Add a global kontra object so TileEngine can access information about the
* loaded assets when kontra is loaded in parts rather than as a whole (e.g.
* `import { load, TileEngine } from 'kontra';`)
*/
function addGlobal() {
if (!window.__k) {
window.__k = {
dm: dataMap,
u: getUrl,
d: dataAssets,
i: imageAssets
};
}
}
/**
* Sets the base path for all image assets. If a base path is set, all load calls for image assets will prepend the base path to the URL.
*
* ```js
* import { setImagePath, load } from 'kontra';
*
* setImagePath('/imgs');
* load('character.png'); // loads '/imgs/character.png'
* ```
* @function setImagePath
*
* @param {String} path - Base image path.
*/
function setImagePath(path) {
imagePath = path;
}
/**
* Sets the base path for all audio assets. If a base path is set, all load calls for audio assets will prepend the base path to the URL.
*
* ```js
* import { setAudioPath, load } from 'kontra';
*
* setAudioPath('/audio');
* load('music.ogg'); // loads '/audio/music.ogg'
* ```
* @function setAudioPath
*
* @param {String} path - Base audio path.
*/
function setAudioPath(path) {
audioPath = path;
}
/**
* Sets the base path for all data assets. If a base path is set, all load calls for data assets will prepend the base path to the URL.
*
* ```js
* import { setDataPath, load } from 'kontra';
*
* setDataPath('/data');
* load('file.json'); // loads '/data/file.json'
* ```
* @function setDataPath
*
* @param {String} path - Base data path.
*/
function setDataPath(path) {
dataPath = path;
}
/**
* Load a single Image asset. Uses the base [image path](api/assets/#setImagePath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [imageAssets](api/assets/#imageAssets) property.
*
* ```js
* import { loadImage } from 'kontra';
*
* loadImage('car.png').then(function(image) {
* console.log(image.src); //=> 'car.png'
* })
* ```
* @function loadImage
*
* @param {String} url - The URL to the Image file.
*
* @returns {Promise} A deferred promise. Promise resolves with the Image.
*/
function loadImage(url) {
addGlobal();
return new Promise((resolve, reject) => {
let resolvedUrl, image, fullUrl;
resolvedUrl = joinPath(imagePath, url);
if (imageAssets[resolvedUrl]) return resolve(imageAssets[resolvedUrl]);
image = new Image();
image.onload = function loadImageOnLoad() {
fullUrl = getUrl(resolvedUrl, window.location.href);
imageAssets[ getName(url) ] = imageAssets[resolvedUrl] = imageAssets[fullUrl] = this;
emit('assetLoaded', this, url);
resolve(this);
};
image.onerror = function loadImageOnError() {
reject(/* @if DEBUG */ 'Unable to load image ' + /* @endif */ resolvedUrl);
};
image.src = resolvedUrl;
});
}
/**
* Load a single Audio asset. Supports loading multiple audio formats which the loader will use to load the first audio format supported by the browser in the order listed. Uses the base [audio path](api/assets/#setAudioPath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [audioAssets](api/assets/#audioAssets) property. Since the loader determines which audio asset to load based on browser support, you should only reference the audio by its name and not by its file path since there's no guarantee which asset was loaded.
*
* ```js
* import { loadAudio, audioAssets } from 'kontra';
*
* loadAudio([
* '/audio/music.mp3',
* '/audio/music.ogg'
* ]).then(function(audio) {
*
* // access audio by its name only (not by its .mp3 or .ogg path)
* audioAssets['/audio/music'].play();
* })
* ```
* @function loadAudio
*
* @param {String} url - The URL to the Audio file.
*
* @returns {Promise} A deferred promise. Promise resolves with the Audio.
*/
function loadAudio(url) {
return new Promise((resolve, reject) => {
let audioEl, canPlay, resolvedUrl, fullUrl;
audioEl = new Audio();
canPlay = getCanPlay(audioEl);
// determine the first audio format the browser can play
url = [].concat(url)
.reduce((playableSource, source) => playableSource
? playableSource
: canPlay[ getExtension(source) ]
? source
: null
, 0); // 0 is the shortest falsy value
if (!url) {
return reject(/* @if DEBUG */ 'cannot play any of the audio formats provided' + /* @endif */ url);
}
resolvedUrl = joinPath(audioPath, url);
if (audioAssets[resolvedUrl]) return resolve(audioAssets[resolvedUrl]);
audioEl.addEventListener('canplay', function loadAudioOnLoad() {
fullUrl = getUrl(resolvedUrl, window.location.href);
audioAssets[ getName(url) ] = audioAssets[resolvedUrl] = audioAssets[fullUrl] = this;
emit('assetLoaded', this, url);
resolve(this);
});
audioEl.onerror = function loadAudioOnError() {
reject(/* @if DEBUG */ 'Unable to load audio ' + /* @endif */ resolvedUrl);
};
audioEl.src = resolvedUrl;
audioEl.load();
});
}
/**
* Load a single Data asset. Uses the base [data path](api/assets/#setDataPath) to resolve the URL.
*
* Once loaded, the asset will be accessible on the the [dataAssets](api/assets/#dataAssets) property.
*
* ```js
* import { loadData } from 'kontra';
*
* loadData('assets/data/tile_engine_basic.json').then(function(data) {
* // data contains the parsed JSON data
* })
* ```
* @function loadData
*
* @param {String} url - The URL to the Data file.
*
* @returns {Promise} A deferred promise. Promise resolves with the contents of the file. If the file is a JSON file, the contents will be parsed as JSON.
*/
function loadData(url) {
addGlobal();
let resolvedUrl, fullUrl;
resolvedUrl = joinPath(dataPath, url);
if (dataAssets[resolvedUrl]) return Promise.resolve(dataAssets[resolvedUrl]);
return fetch(resolvedUrl).then(response => {
if (!response.ok) throw response;
return response.clone().json().catch(() => response.text())
}).then(response => {
fullUrl = getUrl(resolvedUrl, window.location.href);
if (typeof response === 'object') {
dataMap.set(response, fullUrl);
}
dataAssets[ getName(url) ] = dataAssets[resolvedUrl] = dataAssets[fullUrl] = response;
emit('assetLoaded', response, url);
return response;
});
}
/**
* Load Image, Audio, or data files. Uses the [loadImage](api/assets/#loadImage), [loadAudio](api/assets/#loadAudio), and [loadData](api/assets/#loadData) functions to load each asset type.
*
* ```js
* import { load } from 'kontra';
*
* load(
* 'assets/imgs/character.png',
* 'assets/data/tile_engine_basic.json',
* ['/audio/music.ogg', '/audio/music.mp3']
* ).then(function(assets) {
* // all assets have loaded
* }).catch(function(err) {
* // error loading an asset
* });
* ```
* @function load
*
* @param {String|String[]} urls - Comma separated list of asset urls to load.
*
* @returns {Promise} A deferred promise. Resolves with all the loaded assets.
*/
function load(...urls) {
addGlobal();
return Promise.all(
urls.map(asset => {
// account for a string or an array for the url
let extension = getExtension( [].concat(asset)[0] );
return extension.match(imageRegex)
? loadImage(asset)
: extension.match(audioRegex)
? loadAudio(asset)
: loadData(asset);
})
);
}
// expose for testing
// Override the getCanPlay function to provide a specific return type for tests
/**
* Noop function
*/
const noop = () => {};
/**
* Clear the canvas.
*/
function clear() {
let canvas = getCanvas();
getContext().clearRect(0, 0, canvas.width, canvas.height);
}
/**
* The game loop updates and renders the game every frame. The game loop is stopped by default and will not start until the loops `start()` function is called.
*
* The game loop uses a time-based animation with a fixed `dt` to [avoid frame rate issues](http://blog.sklambert.com/using-time-based-animation-implement/). Each update call is guaranteed to equal 1/60 of a second.
*
* This means that you can avoid having to do time based calculations in your update functions and instead do fixed updates.
*
* ```js
* import { Sprite, GameLoop } from 'kontra';
*
* let sprite = Sprite({
* x: 100,
* y: 200,
* width: 20,
* height: 40,
* color: 'red'
* });
*
* let loop = GameLoop({
* update: function(dt) {
* // no need to determine how many pixels you want to
* // move every second and multiple by dt
* // sprite.x += 180 * dt;
*
* // instead just update by how many pixels you want
* // to move every frame and the loop will ensure 60FPS
* sprite.x += 3;
* },
* render: function() {
* sprite.render();
* }
* });
*
* loop.start();
* ```
* @sectionName GameLoop
*
* @param {Object} properties - Properties of the game loop.
* @param {Function} properties.update - Function called every frame to update the game. Is passed the fixed `dt` as a parameter.
* @param {Function} properties.render - Function called every frame to render the game.
* @param {Number} [properties.fps=60] - Desired frame rate.
* @param {Boolean} [properties.clearCanvas=true] - Clear the canvas every frame before the `render()` function is called.
*/
function GameLoop({fps = 60, clearCanvas = true, update, render} = {}) {
// check for required functions
// @if DEBUG
if ( !(update && render) ) {
throw Error('You must provide update() and render() functions');
}
// @endif
// animation variables
let accumulator = 0;
let delta = 1E3 / fps; // delta between performance.now timings (in ms)
let step = 1 / fps;
let clearFn = clearCanvas ? clear : noop;
let last, rAF, now, dt, loop;
/**
* Called every frame of the game loop.
*/
function frame() {
rAF = requestAnimationFrame(frame);
now = performance.now();
dt = now - last;
last = now;
// prevent updating the game with a very large dt if the game were to lose focus
// and then regain focus later
if (dt > 1E3) {
return;
}
emit('tick');
accumulator += dt;
while (accumulator >= delta) {
loop.update(step);
accumulator -= delta;
}
clearFn();
loop.render();
}
// game loop object
loop = {
/**
* Called every frame to update the game. Put all of your games update logic here.
* @memberof GameLoop
* @function update
*
* @param {Number} dt - The fixed dt time of 1/60 of a frame.
*/
update,
/**
* Called every frame to render the game. Put all of your games render logic here.
* @memberof GameLoop
* @function render
*/
render,
/**
* If the game loop is currently stopped.
*
* ```js
* import { GameLoop } from 'kontra';
*
* let loop = GameLoop({
* // ...
* });
* console.log(loop.isStopped); //=> true
*
* loop.start();
* console.log(loop.isStopped); //=> false
*
* loop.stop();
* console.log(loop.isStopped); //=> true
* ```
* @memberof GameLoop
* @property {Boolean} isStopped
*/
isStopped: true,
/**
* Start the game loop.
* @memberof GameLoop
* @function start
*/
start() {
last = performance.now();
this.isStopped = false;
requestAnimationFrame(frame);
},
/**
* Stop the game loop.
* @memberof GameLoop
* @function stop
*/
stop() {
this.isStopped = true;
cancelAnimationFrame(rAF);
},
// expose properties for testing
// @if DEBUG
_frame: frame,
set _last(value) {
last = value;
}
// @endif
};
return loop;
}
/**
* A minimalistic keyboard API. You can use it move the main sprite or respond to a key press.
*
* ```js
* import { initKeys, keyPressed } from 'kontra';
*
* // this function must be called first before keyboard
* // functions will work
* initKeys();
*
* function update() {
* if (keyPressed('left')) {
* // move left
* }
* }
* ```
* @sectionName Keyboard
*/
/**
* Below is a list of keys that are provided by default. If you need to extend this list, you can use the [keyMap](api/keyboard/#keyMap) property.
*
* - a-z
* - 0-9
* - enter, esc, space, left, up, right, down
* @sectionName Available Keys
*/
let callbacks$1 = {};
let pressedKeys = {};
/**
* A map of keycodes to key names. Add to this object to expand the list of [available keys](api/keyboard/#available-keys).
*
* ```js
* import { keyMap, bindKeys } from 'kontra';
*
* keyMap[34] = 'pageDown';
*
* bindKeys('pageDown', function(e) {
* // handle pageDown key
* });
* ```
* @property {Object} keyMap
*/
let keyMap = {
// named keys
13: 'enter',
27: 'esc',
32: 'space',
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
/**
* Execute a function that corresponds to a keyboard key.
*
* @param {KeyboardEvent} evt
*/
function keydownEventHandler(evt) {
let key = keyMap[evt.which];
pressedKeys[key] = true;
if (callbacks$1[key]) {
callbacks$1[key](evt);
}
}
/**
* Set the released key to not being pressed.
*
* @param {KeyboardEvent} evt
*/
function keyupEventHandler(evt) {
pressedKeys[ keyMap[evt.which] ] = false;
}
/**
* Reset pressed keys.
*/
function blurEventHandler() {