-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
1837 lines (1627 loc) · 61.5 KB
/
index.js
File metadata and controls
1837 lines (1627 loc) · 61.5 KB
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
// @ts-check
import { setupZzFX } from './zzfx.js'
import { defaultPalette } from './palette.js'
import { assert } from './dev.js'
import { version } from './version.js'
/**
* The litecanvas constructor
*
* @param {LitecanvasOptions} [settings]
* @returns {LitecanvasInstance}
*/
export default function litecanvas(settings = {}) {
const /** @type {Window} */
root = window,
math = Math,
perf = performance,
TWO_PI = math.PI * 2,
loggerPrefix = '[Litecanvas] ',
raf = requestAnimationFrame,
/** @type {Function[]} */
_browserEventListeners = [],
/** @type {(elem: EventTarget, evt: string, callback: (event: Event) => void) => void} */
on = (elem, evt, callback) => {
elem.addEventListener(evt, callback, false)
_browserEventListeners.push(() => elem.removeEventListener(evt, callback, false))
},
/** @type {(str: string) => string} */
lowerCase = (str) => str.toLowerCase(),
/** @type {(ev: Event) => void} */
preventDefault = (ev) => ev.preventDefault(),
/** @type {(c: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D) => void} */
beginPath = (c) => c.beginPath(),
isNumber = Number.isFinite,
zzfx = setupZzFX(root),
/** @type {LitecanvasOptions} */
defaults = {
width: null,
height: null,
autoscale: true,
canvas: null,
global: true,
loop: null,
tapEvents: true,
keyboardEvents: true,
}
// setup the settings default values
settings = Object.assign(defaults, settings)
let /** @type {boolean} */
_initialized = false,
/** @type {boolean} */
_paused = true,
/** @type {HTMLCanvasElement} _canvas */
_canvas,
/** @type {number} */
_canvasScale = 1,
/** @type {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} */
_ctx,
/** @type {number} */
_outline_fix = 0.5,
/** @type {number} */
_timeScale = 1,
/** @type {number} */
_lastFrameTime,
/** @type {number} duration of a frame at 60 FPS (default) */
_fpsInterval = 1000 / 60,
/** @type {number} */
_accumulated,
/** @type {number?} */
_rafid,
/** @type {number} */
_defaultTextColor = 3,
/** @type {string} */
_fontFamily = 'sans-serif',
/** @type {number} */
_fontSize = 20,
/** @type {number} */
_fontLineHeight = 1.2,
/** @type {number} */
_rngSeed = Date.now(),
/** @type {string[]} */
_colorPalette = defaultPalette,
/** @type {number[]} */
_colorPaletteState = [],
/** @type {number[]} */
_defaultSound = [0.5, 0, 1750, , , 0.3, 1, , , , 600, 0.1],
/** @type {string} list of functions copied from `Math` module*/
_mathFunctions =
'PI,sin,cos,atan2,hypot,tan,abs,ceil,floor,trunc,min,max,pow,sqrt,sign,exp',
/**
* @type {Object<string,Set<Function>>} game event listeners
*/
_eventListeners = {}
/** @type {LitecanvasInstance} */
const instance = {
/** @type {number} */
W: 0,
/** @type {number} */
H: 0,
/** @type {number} */
T: 0,
/** @type {number} */
MX: -1,
/** @type {number} */
MY: -1,
/** MATH API */
/**
* Twice the value of the mathematical constant PI (π).
* Approximately 6.28318
*
* Note: TWO_PI radians equals 360°, PI radians equals 180°,
* HALF_PI radians equals 90°, and HALF_PI/2 radians equals 45°.
*
* @type {number}
*/
TWO_PI,
/**
* Half the value of the mathematical constant PI (π).
* Approximately 1.57079
*
* @type {number}
*/
HALF_PI: TWO_PI / 4,
/**
* Calculates a linear (interpolation) value over t%.
*
* @param {number} start
* @param {number} end
* @param {number} t The progress in percentage, where 0 = 0% and 1 = 100%.
* @returns {number} The unterpolated value
* @tutorial https://gamedev.net/tutorials/programming/general-and-gameplay-programming/a-brief-introduction-to-lerp-r4954/
*/
lerp: (start, end, t) => {
DEV: assert(isNumber(start), loggerPrefix + 'lerp() 1st param must be a number')
DEV: assert(isNumber(end), loggerPrefix + 'lerp() 2nd param must be a number')
DEV: assert(isNumber(t), loggerPrefix + 'lerp() 3rd param must be a number')
return start + t * (end - start)
},
/**
* Convert degrees to radians
*
* @param {number} degs
* @returns {number} the value in radians
*/
deg2rad: (degs) => {
DEV: assert(isNumber(degs), 'deg2rad: 1st param must be a number')
return (math.PI / 180) * degs
},
/**
* Convert radians to degrees
*
* @param {number} rads
* @returns {number} the value in degrees
*/
rad2deg: (rads) => {
DEV: assert(isNumber(rads), 'rad2deg: 1st param must be a number')
return (180 / math.PI) * rads
},
/**
* Returns the rounded value of an number to optional precision (number of digits after the decimal point).
*
* Note: precision is optional but must be >= 0
*
* @param {number} n number to round.
* @param {number} [precision] number of decimal digits to round to, default is 0.
* @returns {number} rounded number.
*/
round: (n, precision = 0) => {
DEV: assert(isNumber(n), loggerPrefix + 'round() 1st param must be a number')
DEV: assert(
isNumber(precision) && precision >= 0,
loggerPrefix + 'round() 2nd param must be a positive number or zero'
)
if (!precision) {
return math.round(n)
}
const multiplier = 10 ** precision
return math.round(n * multiplier) / multiplier
},
/**
* Constrains a number between `min` and `max`.
*
* @param {number} value
* @param {number} min
* @param {number} max
* @returns {number}
*/
clamp: (value, min, max) => {
DEV: assert(isNumber(value), loggerPrefix + 'clamp() 1st param must be a number')
DEV: assert(isNumber(min), loggerPrefix + 'clamp() 2nd param must be a number')
DEV: assert(isNumber(max), loggerPrefix + 'clamp() 3rd param must be a number')
DEV: assert(
max >= min,
loggerPrefix + 'clamp() the 2nd param must be less than the 3rd param'
)
if (value < min) return min
if (value > max) return max
return value
},
/**
* Calculates the distance between a point (x1, y1) to another (x2, y2).
*
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @returns {number}
*/
dist: (x1, y1, x2, y2) => {
DEV: assert(isNumber(x1), loggerPrefix + 'dist() 1st param must be a number')
DEV: assert(isNumber(y1), loggerPrefix + 'dist() 2nd param must be a number')
DEV: assert(isNumber(x2), loggerPrefix + 'dist() 3rd param must be a number')
DEV: assert(isNumber(y2), loggerPrefix + 'dist() 4th param must be a number')
return math.hypot(x2 - x1, y2 - y1)
},
/**
* Wraps a number between `min` (inclusive) and `max` (exclusive).
*
* @param {number} value
* @param {number} min
* @param {number} max
* @returns {number}
*/
wrap: (value, min, max) => {
DEV: assert(isNumber(value), loggerPrefix + 'wrap() 1st param must be a number')
DEV: assert(isNumber(min), loggerPrefix + 'wrap() 2nd param must be a number')
DEV: assert(isNumber(max), loggerPrefix + 'wrap() 3rd param must be a number')
DEV: assert(
max > min,
loggerPrefix + 'wrap() the 2nd param must be less than the 3rd param'
)
return value - (max - min) * math.floor((value - min) / (max - min))
},
/**
* Re-maps a number from one range to another.
*
* @param {number} value the value to be remapped.
* @param {number} start1 lower bound of the value's current range.
* @param {number} stop1 upper bound of the value's current range.
* @param {number} start2 lower bound of the value's target range.
* @param {number} stop2 upper bound of the value's target range.
* @param {boolean} [withinBounds=false] constrain the value to the newly mapped range
* @returns {number} the remapped number
*/
map(value, start1, stop1, start2, stop2, withinBounds) {
DEV: assert(isNumber(value), loggerPrefix + 'map() 1st param must be a number')
DEV: assert(isNumber(start1), loggerPrefix + 'map() 2nd param must be a number')
DEV: assert(isNumber(stop1), loggerPrefix + 'map() 3rd param must be a number')
DEV: assert(isNumber(start2), loggerPrefix + 'map() 4th param must be a number')
DEV: assert(isNumber(stop2), loggerPrefix + 'map() 5th param must be a number')
DEV: assert(
stop1 !== start1,
loggerPrefix + 'map() the 2nd param must be different than the 3rd param'
)
// prettier-ignore
const result = ((value - start1) / (stop1 - start1)) * (stop2 - start2) + start2
return withinBounds ? instance.clamp(result, start2, stop2) : result
},
/**
* Maps a number from one range to a value between 0 and 1.
* Identical to `map(value, min, max, 0, 1)`.
* Note: Numbers outside the range are not clamped to 0 and 1.
*
* @param {number} value
* @param {number} start
* @param {number} stop
* @returns {number} the normalized number.
*/
norm: (value, start, stop) => {
DEV: assert(isNumber(value), loggerPrefix + 'norm() 1st param must be a number')
DEV: assert(isNumber(start), loggerPrefix + 'norm() 2nd param must be a number')
DEV: assert(isNumber(stop), loggerPrefix + 'norm() 3rd param must be a number')
DEV: assert(
start !== stop,
loggerPrefix + 'norm() the 2nd param must be different than the 3rd param'
)
return instance.map(value, start, stop, 0, 1)
},
/** RNG API */
/**
* Generates a pseudorandom float between min (inclusive) and max (exclusive)
* using the Linear Congruential Generator (LCG) algorithm.
*
* @param {number} [min=0.0]
* @param {number} [max=1.0]
* @returns {number} the random number
*/
rand: (min = 0.0, max = 1.0) => {
DEV: assert(isNumber(min), loggerPrefix + 'rand() 1st param must be a number')
DEV: assert(isNumber(max), loggerPrefix + 'rand() 2nd param must be a number')
DEV: assert(
max >= min,
loggerPrefix + 'rand() the 1st param must be less than the 2nd param'
)
const a = 1664525
const c = 1013904223
const m = 4294967296
_rngSeed = (a * _rngSeed + c) % m
return (_rngSeed / m) * (max - min) + min
},
/**
* Generates a pseudorandom integer between min (inclusive) and max (inclusive)
*
* @param {number} [min=0]
* @param {number} [max=1]
* @returns {number} the random number
*/
randi: (min = 0, max = 1) => {
DEV: assert(isNumber(min), loggerPrefix + 'randi() 1st param must be a number')
DEV: assert(isNumber(max), loggerPrefix + 'randi() 2nd param must be a number')
DEV: assert(
max >= min,
loggerPrefix + 'randi() the 1st param must be less than the 2nd param'
)
return ~~instance.rand(min, max + 1)
},
/**
* Initializes the random number generator with an explicit seed value.
*
* Note: The seed should be a integer number greater than or equal to zero.
*
* @param {number} value
*/
rseed(value) {
DEV: assert(
isNumber(value) && value >= 0,
loggerPrefix + 'rseed() 1st param must be a positive integer or zero'
)
_rngSeed = ~~value
},
/** BASIC GRAPHICS API */
/**
* Clear the game screen with an optional color
*
* @param {number} [color] The background color (index) or null/undefined (for transparent)
*/
cls(color) {
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'cls() 1st param must be a positive number or zero or undefined'
)
if (null == color) {
_ctx.clearRect(0, 0, instance.W, instance.H)
} else {
instance.rectfill(0, 0, instance.W, instance.H, color)
}
},
/**
* Draw a rectangle outline
*
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {number} [color=0] the color index
* @param {number|number[]} [radii] A number or list specifying the radii used to draw a rounded-borders rectangle
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/roundRect
*/
rect(x, y, width, height, color, radii) {
DEV: assert(isNumber(x), loggerPrefix + 'rect() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'rect() 2nd param must be a number')
DEV: assert(
isNumber(width) && width > 0,
loggerPrefix + 'rect() 3rd param must be a positive number'
)
DEV: assert(
isNumber(height) && height >= 0,
loggerPrefix + 'rect() 4th param must be a positive number or zero'
)
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'rect() 5th param must be a positive number or zero'
)
DEV: assert(
null == radii || isNumber(radii) || (Array.isArray(radii) && radii.length >= 1),
loggerPrefix + 'rect() 6th param must be a number or array of numbers'
)
beginPath(_ctx)
_ctx[radii ? 'roundRect' : 'rect'](
~~x - _outline_fix,
~~y - _outline_fix,
~~width + _outline_fix * 2,
~~height + _outline_fix * 2,
radii
)
instance.stroke(color)
},
/**
* Draw a color-filled rectangle
*
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {number} [color=0] the color index
* @param {number|number[]} [radii] A number or list specifying the radii used to draw a rounded-borders rectangle
*/
rectfill(x, y, width, height, color, radii) {
DEV: assert(isNumber(x), loggerPrefix + 'rectfill() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'rectfill() 2nd param must be a number')
DEV: assert(
isNumber(width) && width >= 0,
loggerPrefix + 'rectfill() 3rd param must be a positive number or zero'
)
DEV: assert(
isNumber(height) && height >= 0,
loggerPrefix + 'rectfill() 4th param must be a positive number or zero'
)
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'rectfill() 5th param must be a positive number or zero'
)
DEV: assert(
null == radii || isNumber(radii) || (Array.isArray(radii) && radii.length >= 1),
loggerPrefix +
'rectfill() 6th param must be a number or array of at least 2 numbers'
)
beginPath(_ctx)
_ctx[radii ? 'roundRect' : 'rect'](~~x, ~~y, ~~width, ~~height, radii)
instance.fill(color)
},
/**
* Draw a circle outline
*
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} [color=0] the color index
*/
circ(x, y, radius, color) {
DEV: assert(isNumber(x), loggerPrefix + 'circ() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'circ() 2nd param must be a number')
DEV: assert(
isNumber(radius) && radius >= 0,
loggerPrefix + 'circ() 3rd param must be a positive number or zero'
)
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'circ() 4th param must be a positive number or zero'
)
beginPath(_ctx)
_ctx.arc(~~x, ~~y, ~~radius, 0, TWO_PI)
instance.stroke(color)
},
/**
* Draw a color-filled circle
*
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} [color=0] the color index
*/
circfill(x, y, radius, color) {
DEV: assert(isNumber(x), loggerPrefix + 'circfill() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'circfill() 2nd param must be a number')
DEV: assert(
isNumber(radius) && radius >= 0,
loggerPrefix + 'circfill() 3rd param must be a positive number or zero'
)
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'circfill() 4th param must be a positive number or zero'
)
beginPath(_ctx)
_ctx.arc(~~x, ~~y, ~~radius, 0, TWO_PI)
instance.fill(color)
},
/**
* Draw a ellipse outline
*
* @param {number} x
* @param {number} y
* @param {number} radiusX
* @param {number} radiusY
* @param {number} [color=0] the color index
*/
oval(x, y, radiusX, radiusY, color) {
DEV: assert(isNumber(x), loggerPrefix + 'oval() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'oval() 2nd param must be a number')
DEV: assert(
isNumber(radiusX) && radiusX >= 0,
loggerPrefix + 'oval() 3rd param must be a positive number or zero'
)
DEV: assert(
isNumber(radiusY) && radiusY >= 0,
loggerPrefix + 'oval() 4th param must be a positive number or zero'
)
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'oval() 5th param must be a positive number or zero'
)
beginPath(_ctx)
_ctx.ellipse(~~x, ~~y, ~~radiusX, ~~radiusY, 0, 0, TWO_PI)
instance.stroke(color)
},
/**
* Draw a color-filled ellipse
*
* @param {number} x
* @param {number} y
* @param {number} radiusX
* @param {number} radiusY
* @param {number} [color=0] the color index
*/
ovalfill(x, y, radiusX, radiusY, color) {
DEV: assert(isNumber(x), loggerPrefix + 'ovalfill() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'ovalfill() 2nd param must be a number')
DEV: assert(
isNumber(radiusX) && radiusX >= 0,
loggerPrefix + 'ovalfill() 3rd param must be a positive number or zero'
)
DEV: assert(
isNumber(radiusY) && radiusY >= 0,
loggerPrefix + 'ovalfill() 4th param must be a positive number or zero'
)
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'ovalfill() 5th param must be a positive number or zero'
)
beginPath(_ctx)
_ctx.ellipse(~~x, ~~y, ~~radiusX, ~~radiusY, 0, 0, TWO_PI)
instance.fill(color)
},
/**
* Make a custom shape in the canvas context.
* Then, just use `fill` or `stroke` to draw the shape.
*
* @param {number[]} points an array of Xs and Ys coordinates
*/
shape(points) {
DEV: assert(
Array.isArray(points),
loggerPrefix + 'shape() 1st param must be an array of numbers'
)
DEV: assert(
points.length >= 6,
loggerPrefix +
'shape() 1st param must be an array with at least 6 numbers (3 points)'
)
beginPath(_ctx)
for (let i = 0; i < points.length; i += 2) {
if (0 === i) {
_ctx.moveTo(~~points[i], ~~points[i + 1])
} else {
_ctx.lineTo(~~points[i], ~~points[i + 1])
}
}
_ctx.lineTo(~~points[0], ~~points[1])
},
/**
* Draw a line
*
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} [color=0] the color index
*/
line(x1, y1, x2, y2, color) {
DEV: assert(isNumber(x1), loggerPrefix + 'line() 1st param must be a number')
DEV: assert(isNumber(y1), loggerPrefix + 'line() 2nd param must be a number')
DEV: assert(
isNumber(x2),
loggerPrefix + 'line() 3rd param must be a positive number or zero'
)
DEV: assert(
isNumber(y2),
loggerPrefix + 'line() 4th param must be a positive number or zero'
)
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'line() 5th param must be a positive number or zero'
)
beginPath(_ctx)
let xfix = _outline_fix !== 0 && ~~x1 === ~~x2 ? 0.5 : 0
let yfix = _outline_fix !== 0 && ~~y1 === ~~y2 ? 0.5 : 0
_ctx.moveTo(~~x1 + xfix, ~~y1 + yfix)
_ctx.lineTo(~~x2 + xfix, ~~y2 + yfix)
instance.stroke(color)
},
/**
* Sets the thickness of the lines
*
* @param {number} value
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineWidth
*/
linewidth(value) {
DEV: assert(
isNumber(value) && value >= 0,
loggerPrefix + 'linewidth() 1st param must be a positive number or zero'
)
_ctx.lineWidth = ~~value
_outline_fix = 0 === ~~value % 2 ? 0 : 0.5
},
/**
* Sets the line dash pattern used when drawing lines
*
* @param {number[]} segments the line dash pattern
* @param {number} [offset=0] the line dash offset, or "phase".
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
*/
linedash(segments, offset = 0) {
DEV: assert(
Array.isArray(segments) && segments.length > 0,
loggerPrefix + 'linedash() 1st param must be an array of numbers'
)
DEV: assert(isNumber(offset), loggerPrefix + 'linedash() 2nd param must be a number')
_ctx.setLineDash(segments)
_ctx.lineDashOffset = offset
},
/** TEXT RENDERING API */
/**
* Draw text. You can use `\n` to break lines.
*
* @param {number} x
* @param {number} y
* @param {string} message the text message
* @param {number} [color] the color index
* @param {string} [fontStyle] can be "normal" (default), "italic" and/or "bold".
*/
text(x, y, message, color = _defaultTextColor, fontStyle = 'normal') {
DEV: assert(isNumber(x), loggerPrefix + 'text() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'text() 2nd param must be a number')
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'text() 4th param must be a positive number or zero'
)
DEV: assert(
'string' === typeof fontStyle,
loggerPrefix + 'text() 5th param must be a string'
)
_ctx.font = `${fontStyle} ${_fontSize}px ${_fontFamily}`
_ctx.fillStyle = getColor(color)
const messages = ('' + message).split('\n')
for (let i = 0; i < messages.length; i++) {
_ctx.fillText(messages[i], ~~x, ~~y + _fontSize * _fontLineHeight * i)
}
},
/**
* Sets the height ratio of the text lines based on current text size.
*
* Default = `1.2`
*
* @param value
*/
textgap(value) {
_fontLineHeight = value
},
/**
* Set the font family
*
* @param {string} family
*/
textfont(family) {
DEV: assert(
'string' === typeof family,
loggerPrefix + 'textfont() 1st param must be a string'
)
_fontFamily = family
},
/**
* Set the font size
*
* @param {number} size
*/
textsize(size) {
DEV: assert(isNumber(size), loggerPrefix + 'textsize() 1st param must be a number')
_fontSize = size
},
/**
* Sets the alignment used when drawing texts
*
* @param {CanvasTextAlign} align the horizontal alignment. Possible values: "left", "right", "center", "start" or "end"
* @param {CanvasTextBaseline} baseline the vertical alignment. Possible values: "top", "bottom", "middle", "hanging" or "ideographic"
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textAlign
*/
textalign(align, baseline) {
DEV: assert(
null == align || ['left', 'right', 'center', 'start', 'end'].includes(align),
loggerPrefix +
'textalign() 1st param must be null or one of the following strings: center, left, right, start or end.'
)
DEV: assert(
null == baseline ||
['top', 'bottom', 'middle', 'hanging', 'alphabetic', 'ideographic'].includes(
baseline
),
loggerPrefix +
'textalign() 2nd param must be null or one of the following strings: middle, top, bottom, hanging, alphabetic or ideographic.'
)
if (align) _ctx.textAlign = align
if (baseline) _ctx.textBaseline = baseline
},
/** IMAGE GRAPHICS API */
/**
* Draw an image
*
* @param {number} x
* @param {number} y
* @param {CanvasImageSource} source
*/
image(x, y, source) {
DEV: assert(isNumber(x), loggerPrefix + 'image() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'image() 2nd param must be a number')
_ctx.drawImage(source, ~~x, ~~y)
},
/**
* Draw a sprite pixel by pixel represented by a string. Each pixel must be a base 36 number (0-9 or a-z) or a dot.
*
* @param {number} x
* @param {number} y
* @param {string} pixels
*/
spr(x, y, pixels) {
DEV: assert(isNumber(x), loggerPrefix + 'spr() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'spr() 2nd param must be a number')
DEV: assert(
'string' === typeof pixels,
loggerPrefix + 'spr() 3rd param must be a string'
)
const rows = pixels.trim().split('\n')
for (let row = 0; row < rows.length; row++) {
const chars = rows[row].trim()
for (let col = 0; col < chars.length; col++) {
const char = chars[col]
if (char !== '.' && char !== ' ') {
instance.rectfill(x + col, y + row, 1, 1, parseInt(char, 36) || 0)
}
}
}
},
/**
* Draw in an OffscreenCanvas and returns its image.
*
* @param {number} width
* @param {number} height
* @param {drawCallback} callback
* @param {object} [options]
* @param {number} [options.scale=1]
* @param {OffscreenCanvas} [options.canvas]
* @returns {ImageBitmap}
* @see https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas
*/
paint(width, height, callback, options = {}) {
DEV: assert(
isNumber(width) && width >= 1,
loggerPrefix + 'paint() 1st param must be a positive number'
)
DEV: assert(
isNumber(height) && height >= 1,
loggerPrefix + 'paint() 2nd param must be a positive number'
)
DEV: assert(
'function' === typeof callback,
loggerPrefix + 'paint() 3rd param must be a function'
)
DEV: assert(
(options && null == options.scale) || isNumber(options.scale),
loggerPrefix + 'paint() 4th param (options.scale) must be a number'
)
DEV: assert(
(options && null == options.canvas) || options.canvas instanceof OffscreenCanvas,
loggerPrefix + 'paint() 4th param (options.canvas) must be an OffscreenCanvas'
)
const /** @type {OffscreenCanvas} */
canvas = options.canvas || new OffscreenCanvas(1, 1),
scale = options.scale || 1,
currentContext = _ctx // context backup
canvas.width = width * scale
canvas.height = height * scale
_ctx = canvas.getContext('2d')
_ctx.scale(scale, scale)
callback(_ctx)
_ctx = currentContext // restore the context
return canvas.transferToImageBitmap()
},
/** ADVANCED GRAPHICS API */
/**
* Get or set the canvas context 2D
*
* @param {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D} [context]
* @returns {CanvasRenderingContext2D|OffscreenCanvasRenderingContext2D}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
*/
ctx(context) {
if (context) {
_ctx = context
}
return _ctx
},
/**
* saves the current drawing style settings and transformations
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/save
*/
push() {
_ctx.save()
},
/**
* restores the drawing style settings and transformations
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/restore
*/
pop() {
_ctx.restore()
},
/**
* Adds a translation to the transformation matrix.
*
* @param {number} x
* @param {number} y
*/
translate(x, y) {
DEV: assert(isNumber(x), loggerPrefix + 'translate() 1st param must be a number')
DEV: assert(isNumber(y), loggerPrefix + 'translate() 2nd param must be a number')
_ctx.translate(~~x, ~~y)
},
/**
* Adds a scaling transformation to the canvas units horizontally and/or vertically.
*
* @param {number} x
* @param {number} [y]
*/
scale(x, y) {
DEV: assert(isNumber(x), loggerPrefix + 'scale() 1st param must be a number')
DEV: assert(
null == y || isNumber(y),
loggerPrefix + 'scale() 2nd param must be a number'
)
_ctx.scale(x, y || x)
},
/**
* Adds a rotation to the transformation matrix.
*
* @param {number} radians
*/
rotate(radians) {
DEV: assert(isNumber(radians), loggerPrefix + 'rotate() 1st param must be a number')
_ctx.rotate(radians)
},
/**
* Sets the alpha (opacity) value to apply when drawing new shapes and images
*
* @param {number} value float from 0 to 1 (e.g: 0.5 = 50% transparent)
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalAlpha
*/
alpha(value) {
DEV: assert(isNumber(value), loggerPrefix + 'alpha() 1st param must be a number')
_ctx.globalAlpha = instance.clamp(value, 0, 1)
},
/**
* Fills the current path with a given color.
*
* @param {number} [color=0]
*/
fill(color) {
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'fill() 1st param must be a positive number or zero'
)
_ctx.fillStyle = getColor(color)
_ctx.fill()
},
/**
* Outlines the current path with a given color.
*
* @param {number} [color=0]
*/
stroke(color) {
DEV: assert(
null == color || (isNumber(color) && color >= 0),
loggerPrefix + 'stroke() 1st param must be a positive number or zero'
)
_ctx.strokeStyle = getColor(color)
_ctx.stroke()
},
/**
* Turns a path (in the callback) into the current clipping region.
*
* @param {clipCallback} callback
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clip
*/
clip(callback) {
DEV: assert(
'function' === typeof callback,
loggerPrefix + 'clip() 1st param must be a function'
)
beginPath(_ctx)
callback(_ctx)
_ctx.clip()
},
/** SOUND API */
/**
* Play a sound effects using ZzFX library.
* If the first argument is omitted, plays an default sound.
*
* @param {number[]} [zzfxParams] a ZzFX array of params
* @param {number} [pitchSlide] a value to increment/decrement the pitch
* @param {number} [volumeFactor] the volume factor