-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.js
1532 lines (1518 loc) · 40.7 KB
/
main.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
/*
ski.js
version 1.9.x
*/
var CORNER, CENTER, CLOSE, SPACE, LEFT, RIGHT, UP, DOWN, SQUARE, ROUND, PROJECT, MITER, BEVEL, DEGREES, RADIANS, PI, TAU, RGBA, HSL, HEX, LEFT_BUTTON, RIGHT_BUTTON, ESCAPE, TAB, SHIFT, CONTROL, ALT, ENTER, BACKSPACE, fps, skiJSData, canvas, ctx, mousePressed, mouseReleased, mouseScrolled, mouseClicked, mouseOver, mouseOut, mouseMoved, mouseIsPressed, mouseButton, mouseX, mouseY, pmouseX, pmouseY, keyPressed, keyReleased, keyTyped, key, keyIsPressed, keyCode, width, height
// constants
// KeyEvent.keyCode values
BACKSPACE = 8
TAB = 9
ENTER = 13
SHIFT = 16
CONTROL = 17
ALT = 18
ESCAPE = 27
SPACE = 32
LEFT = 37
RIGHT = 39
UP = 38
DOWN = 40
//mostly for drawin' stuff on the canvas
CORNER = 0
CENTER = 1
CLOSE = true
SQUARE = atob("YnV0dA==") //yeah, srsly.
ROUND = "round"
PROJECT = "square"
MITER = "iter"
BEVEL = "bevel"
DEGREES = "deg"
RADIANS = "rad"
PI = Math.PI
TAU = PI * 2
RGBA = "rgba"
HSL = "hsl"
HEX = "hex"
LEFT_BUTTON = 0
RIGHT_BUTTON = 2
// setup the canvas
canvas = null
ctx = null
//all canvas-related functions
/**
* sets the canvas width an' height.
* @param {number} w - width
* @param {number} h - height
* @param {boolean} [css=false] - whether to set the dimensions of the canvas or just the resolution
* @example
* size(600, 600)
* //resizes the resolution of the canvas to 600px by 600px
* size(600, 600, true)
* //resizes the resolution an' dimension of the canvas to 600px by 600px
**/
function size (w, h, css) {
if (!canvas || !ctx) {
canvas = document.querySelectorAll("canvas,canvas.skijs,canvas[data-skijs]")[0]
set(canvas)
}
width = canvas.width = w
height = canvas.height = h
css && (canvas.style.width = `${w}px`, canvas.style.height = `${h}px`)
}
/**
* sets the current canvas to a different canvas, whether off or on screen
*
* xxx HS16 - Now attaches the proper event listeners to the canvas.
*
* @param {...(HTMLCanvasElement|OffscreenCanvas|number)} [args] - argument for the set function
* @example
* set()
* //sets the canvas to a new OffscreenCanvas with the same width an' height of the current canvas
* set(document.getElementsByTagName("canvas")[0])
* //set the canvas to the first canvas element in the DOM
* set(400, 400)
* //sets the canvas to a new OffscreenCanvas with dimensions 400px by 400px
**/
function set (...args) {
switch (args.length) {
case 0:
rejectCanvas()
canvas = new OffscreenCanvas(width, height)
ctx = canvas.getContext("2d")
adoptCanvas();
return [canvas, ctx]
break
case 1:
rejectCanvas()
canvas = args[0]
ctx = canvas.getContext("2d")
width = canvas.width
height = canvas.height
adoptCanvas();
break
case 2:
rejectCanvas()
canvas = new OffscreenCanvas(args[0], args[1])
ctx = canvas.getContext("2d")
width = args[0]
height = args[1]
adoptCanvas()
return [canvas, ctx]
}
}
/**
* sets the background for the canvas
* @param {...(string|number|Array)} args
* @see {@link color} for the definition of the arguments
**/
function background (...args) {
const cache = [ctx.strokeStyle, ctx.fillStyle]
const matrix = ctx.getTransform()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.strokeStyle = "rgba(0, 0, 0, 0)"
ctx.fillStyle = color(...args)
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.strokeStyle = cache[0]
ctx.fillStyle = cache[1]
ctx.setTransform(matrix)
}
/**
* sets the fill color for the shapes following the call
* @param {...(string|number|Array)} args
* @see {@link color} for the definition of the arguments
**/
function fill (...args) {
ctx.fillStyle = color(...args)
}
/**
* sets the fill color for the shapes following the call
* @param {...(string|number|Array)} args
* @see {@link color} for the definition of the arguments
**/
function stroke (...args) {
ctx.strokeStyle = color(...args)
}
/**
* draws an ImageData object, HTMLCanvasElement, or HTMLImageElement on the canvas
* @param {(HTMLCanvasElement|ImageData|HTMLImageElement)} img image to be drawn
* @param {number} x
* @param {number} y
* @param {number} [w=img.width] - the width of the image. defaults to the width of the image. i mean what else would it default too lol?
* @param {number} [h=img.height] - the height of the image. defaults to the height of the image. i mean what else would it default too lol?
* @example
* image(img, 0, 0)
* //draws the image at (0, 0) with the default width an' height
* image(img, 0, 0)
* //draws the image at (0, 0) with the dimensions 400px by 400px
**/
function image (img, x, y, w = img.width, h = img.height) {
[x, y] = skiJSData.pos("image", x, y, w, h)
if(img instanceof ImageData) ctx.putImageData(img, x, y, w, h)
else ctx.drawImage(img, x, y, w, h)
}
/**
* draws a clear rectangle across the entire canvas
**/
function clear () {
const matrix = ctx.getTransform()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, width, height)
ctx.setTransform(matrix)
}
/**
* removes any stroke from the shapes to be drawn after the function call
**/
function noStroke () {
ctx.strokeStyle = color(0, 0)
}
/**
* removes any stroke from the shapes to be drawn after the function call
**/
function noFill () {
ctx.fillStyle = color(0, 0)
}
/**
* draws a rectangle on the canvas
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
* @param {...number} radius - radius or radii. basically works the same as [`ctx.roundRect`]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/roundRect}
* @example
* rect(0, 0, 10, 10)
* //draws a rectangle at (0, 0) with dimensions 10px by 10px
**/
function rect (x, y, width, height, ...radius) {
[x, y] = skiJSData.pos("rect", x, y, width, height)
if (radius.length > 0) {
ctx.beginPath()
ctx.roundRect(x, y, width, height, ...radius)
ctx.closePath()
ctx.stroke()
ctx.fill()
} else {
ctx.fillRect(x, y, width, height)
ctx.strokeRect(x, y, width, height)
}
}
/**
* i see absolutely no reason why you would document this, .-.
* it's a helper function for the [text function]{@link text}.
*
* @param {string} str - a string
* @param {number} width - the width of the text
*
* @returns {string} - the string with proper line breaks.
**/
function wrapText (str, width) {
str = str.split(/[ ]/)
let i = 0, phrase = "", result = ""
while(i < str.length){
const frag = str[i]
const newLineCharIndex = frag.indexOf("\n")
if(newLineCharIndex >= 0){
phrase += frag.slice(0, newLineCharIndex + 1)
result += phrase
phrase = frag.slice(newLineCharIndex + 1, frag.length) + " "
}
else {
phrase += frag + " "
if(textWidth(phrase) > width){
result += phrase + "\n"
phrase = ""
}
}
i++
}
if(phrase.length > 0){
result += "\n" + phrase
}
return result
}
/**
* displays text on the canvas
* @param {!*} msg the message you want to display can be anythin' but null.
* @param {number} x
* @param {number} y
* @param {number} [w] width
* @param {number} [h] height - (this doesn't do anythin')
* @example
* textAlign(CENTER, CENTER)
* text("hello there!", width / 2, height / 2)
* //draws "hello there!" on the center of the canvas
* text("hello there!", width / 2, height / 2, 200, 100)
* //draws "hello there!" on the center of the canvas with a maximum width of 200px
**/
function text (msg, x, y, w, h) {
msg = msg?.toString()
if(w) msg = wrapText(msg, w)
if (msg.includes("\n")) {
msg.split("\n").map((p, i) => {
ctx.fillText(p, x, y + ((i - ((msg.split("\n")).length - 1) / 2) * (skiJSData.height + skiJSData.leading)))
ctx.strokeText(p, x, y + ((i - ((msg.split("\n")).length - 1) / 2) * (skiJSData.height + skiJSData.leading)))
})
} else {
ctx.fillText(msg, x, y)
ctx.strokeText(msg, x, y)
}
}
/**
* sets the positionin' mode for rectangles
* @param {number} [m=CORNER] - mode; please only use CORNER an' CENTER or 0 an' 1
* @example
* rectMode(CORNER)
* //draws rectangles from the top-left corner
* rectMode(CENTER)
* //draws rectangles from their center
**/
function rectMode (m) {
skiJSData.rect = m
}
/**
* sets the positionin' mode for ellipses
* @param {number} [m=CENTER] - mode; please only use CORNER an' CENTER or 0 an' 1
* @example
* ellipseMode(CORNER)
* //draws ellipses from the top-left corner
* ellipseMode(CENTER)
* //draws ellipses from their center
**/
function ellipseMode (m) {
skiJSData.ellipse = m
}
/**
* sets the positionin' mode for arcs
* @param {number} [m=CENTER] - mode; please only use CORNER an' CENTER or 0 an' 1
* @example
* arcMode(CORNER)
* //draws arcs from the top-left corner
* arcMode(CENTER)
* //draws arcs from their center
**/
function arcMode (m) {
skiJSData.arc = m
}
/**
* sets the positionin' mode for images
* @param {number} [m=CORNER] - mode; please only use CORNER an' CENTER or 0 an' 1
* @example
* imageMode(CORNER)
* //draws rectangles from the top-left corner
* imageMode(CENTER)
* //draws rectangles from their center
**/
function imageMode (m) {
skiJSData.image = m
}
/**
* aligns the text drawn on the canvas
* @param {number} [horiztonal=CORNER] - horizontal alignment
* @param {number} [vertical=CORNER] - vertical alignment
* @example
* textAlign(CENTER, CENTER)
* //text will now be drawn from the center
**/
function textAlign (horizontal, vertical) {
//println(horizontal === CENTER, vertical === CENTER)
ctx.textAlign = horizontal === CENTER ? "center" : "start"
ctx.textBaseline = vertical === CENTER ? "middle" : "hanging"
}
/**
* do NOT use this function! this is simply for PJS compatibility.
* it's useless, just returns whatever you input as an argument.
* @param {string} font
* @return {string} font
**/
function createFont (font) {
return font
}
/**
* sets the font size for any text drawn
* @param {number} size
* @example
* textSize(20)
* //text will be drawn at 20px
**/
function textSize (size) {
skiJSData.height = size
ctx.font = skiJSData.fontString(skiJSData.font, size)
}
/**
* sets the font for any text drawn
* @param {string} font - the name of the font
* @param {number} [size] - the size of the font in px
* @example
* textFont("Arial", 12)
* //font is arial with size 12px
**/
function textFont (font, size = skiJSData.height) {
skiJSData.height !== size && (skiJSData.height = size)
skiJSData.flags = []
if ((/bold/i).test(font)) {
skiJSData.flags.push("bold")
font = font.replace("bold", '')
}
if ((/italic/i).test(font)) {
skiJSData.flags.push("italic")
font = font.replace("italic", '')
}
font = font.trim()
skiJSData.font = font
ctx.font = skiJSData.fontString(font, size)
}
/**
* sets the space between text on the y-axis
* @param {number} val - leading in pix
**/
function textLeading (val) {
skiJSData.leading = val
}
/**
* find the width of a string given the current font an' font size
* for strings with line breaks, it finds the largest width
* @param {string} txt - text
**/
function textWidth (txt) {
return txt.split("\n").reduce((a, b) => max(a, ctx.measureText(b).width), 0)
}
/**
* i honestly don't know. just ported the concept from PJS.
**/
function textAscent () {
return ctx.measureText("a").fontBoundingBoxAscent
}
/**
* i honestly don't know. just ported the concept from PJS.
**/
function textDescent () {
ctx.measureText("a").fontBoundingBoxDescent
}
/**
* sets the stroke cap. see [`ctx.lineCap`]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap}
* @param {string} mode - line cap value; use ski.js constants
**/
function strokeCap (mode) {
ctx.lineCap = mode
}
/**
* sets the stroke cap. see [`ctx.lineJoin`]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin}
* @param {string} mode - line join value; use ski.js constants
**/
function strokeJoin (mode) {
ctx.lineJoin = mode
}
/**
* sets the stroke cap. see [`ctx.lineWidth`]{@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineWidth}
* @param {string} weight - line width value; use ski.js constants
**/
function strokeWeight (weight) {
ctx.lineWidth = weight
}
/**
* saves the current state of the canvas
**/
function pushStyle () {
ctx.save()
}
/**
* restores the saved state of the canvas
**/
function popStyle () {
ctx.restore()
}
/**
* save the current transformation matrix state
**/
function pushMatrix () {
const { matrices: arr, matrixToArray: convert } = skiJSData
arr.push(convert(ctx.getTransform()))
}
/**
* restores the saved transformation matrix state
**/
function popMatrix () {
const arr = new Float32Array(skiJSData.matrices.pop())
const mat = DOMMatrix.fromFloat32Array(arr)
ctx.setTransform(mat)
}
/**
* translate given coordinates
* @param {number} x
* @param {number} y
**/
function translate (x, y) {
ctx.transform(1, 0, 0, 1, x, y)
}
/**
* rotate given an angle
* @param {number} ang - rotation angle
**/
function rotate (ang) {
if(skiJSData.angle === DEGREES) ang = degrees(ang)
const cos = Math.cos, sin = Math.sin
ctx.transform(cos(ang), sin(ang), -sin(ang), cos(ang), 0, 0)
}
/**
* scale given a factor
* @param {number} w - if only one arg, the scale factor; else the x scale factor.
* @param {number} [h] - y scale factor
**/
function scale (w, h) {
ctx.transform(w, 0, 0, h ? h : w, 0, 0)
}
/**
* starts a new shape
**/
function beginShape () {
skiJSData.path = []
}
/**
* adds a vertex to a shape
* @param {number} x
* @param {number} y
**/
function vertex (x, y) {
skiJSData.path.push([x, y])
}
/**
* adds a curve vertex to a shape
* a quadratic curve, a singular control point an' an endpoint.
* @param {number} cx - control x
* @param {number} cy - control y
* @param {number} x
* @param {number} y
**/
function curveVertex (cx, cy, x, y) {
skiJSData.path.push([cx, cy, x, y])
}
/**
* adds a bezier vertex to a shape
* a bezier curve, two control points an' one endpoint
* @param {number} c1x - control x 1
* @param {number} c1y - control y 1
* @param {number} c2x - control x 2
* @param {number} c2y - control y 2
* @param {number} x
* @param {number} y
**/
function bezierVertex (c1x, c1y, c2x, c2y, x, y) {
skiJSData.path.push([c1x, c1y, c2x, c2y, x, y])
}
/**
* ends the shape calls an' draws a shape.
* this could be abused to draw the same shape again
* 'cuz i don't clear the path, semi-intentionally.
*
* @param {boolean} [end] - use CLOSE, closes a shape by callin' ctx.closePath
**/
function endShape (end) {
const paths = skiJSData.path
if (paths.length < 2 || paths[0].length !== 2) return
ctx.beginPath()
paths.forEach((path, index) => {
if(index === 0){
ctx.moveTo(...path)
}
else {
if(path.length === 2) ctx.lineTo(...path)
else if(path.length === 4) ctx.quadraticCurveTo(...path)
else if(path.length === 6) ctx.bezierCurveTo(...path)
else return
}
})
if(end) ctx.closePath()
ctx.fill()
ctx.stroke()
}
/**
* draws a curve given six points.
* called in this order: vertex -> curveVertex
* @param {number} sx - start x
* @param {number} sy - start y
* @param {number} cx - control x
* @param {number} cy - control y
* @param {number} ex - end x
* @param {number} ey - end y
**/
function curve (sx, sy, cx, cy, ex, ey) {
if (typeof ey !== "number") return
beginShape()
vertex(sx, sy)
curveVertex(cx, cy, ex, ey)
endShape()
}
/**
* draws a curve given eight points.
* called in this order: vertex -> bezierVertex
* @param {number} sx - start x
* @param {number} sy - start y
* @param {number} c1x - control x 1
* @param {number} c1y - control y 1
* @param {number} c2x - contorl x 2
* @param {number} c2y - control y 2
* @param {number} ex - end x
* @param {number} ey - end y
**/
function bezier (sx, sy, c1x, c1y, c2x, c2y, ex, ey) {
if (typeof ey !== "number") return
beginShape()
vertex(sx, sy)
bezierVertex(c1x, c1y, c2x, c2y, ex, ey)
endShape()
}
/**
* draws an arc.
* @param {number} x
* @param {number} y
* @param {number} w - width
* @param {number} h - width
* @param {number} start - start angle
* @param {number} stop - stop angle
* @param {boolean} [close=false] - call endShape(CLOSE)
**/
function arc (x, y, w, h, start, stop, close = false) {
[x, y] = skiJSData.pos("arc", x, y, width, height)
pushMatrix()
translate(x, y)
if(w !== h){
if(w > h) scale(max(w, h) / min(w, h), 1)
else scale(1, max(w, h) / min(w, h))
}
ctx.beginPath()
if(ctx.fillStyle !== color(0, 0)) ctx.moveTo(0, 0)
ctx.arc(0, 0, min(w, h) / 2, degrees(start), degrees(stop))
if(close) ctx.closePath()
popMatrix()
ctx.fill()
ctx.stroke()
}
/**
* draws an ellipse or circle
* @param {number} x
* @param {number} y
* @param {number} w - width
* @param {number} h - height
**/
function ellipse (x, y, w, h) {
ctx.beginPath()
ctx.ellipse(x, y, w / 2, h / 2, 0, 0, TAU)
ctx.fill()
ctx.stroke()
}
/**
* draws a quadrilateral usin' vertex
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} x3
* @param {number} y3
* @param {number} x4
* @param {number} y4
**/
function quad (x1, y1, x2, y2, x3, y3, x4, y4) {
beginShape()
vertex(x1, y1)
vertex(x2, y2)
vertex(x3, y3)
vertex(x4, y4)
endShape(CLOSE)
}
/**
* draws a triangle
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} x3
* @param {number} y3
**/
function triangle (x1, y1, x2, y2, x3, y3) {
beginShape()
vertex(x1, y1)
vertex(x2, y2)
vertex(x3, y3)
endShape(CLOSE)
}
/**
* draws a point with stroke
* @param {number} x
* @param {number} y
**/
function point (x, y) {
if (ctx.strokeStyle !== color(0, 0)) {
const cache = [ctx.strokeStyle, ctx.fillStyle]
noStroke()
ctx.fillStyle = cache[0]
ellipse(x, y, ctx.lineWidth, ctx.lineWidth)
ctx.strokeStyle = cache[0]
ctx.fillStyle = cache[1]
}
}
/**
* draws a line
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
**/
function line (x1, y1, x2, y2) {
ctx.beginPath()
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.closePath()
ctx.stroke()
}
/**
* returns the ImageData for the given canvas, coordinates an' dimensions
* @param {...(number|HTMLCanvasElement|OffscreenCanvas)} args - [x, y, width, height, sourceCanvas]
* @returns {(ImageData|string)} - the color or ImageData object
* @example
* get()
* //same as get(0, 0, width, height)
* get(0, 0)
* //returns the color of the pixel at (0, 0)
* get(canvas, 0, 0)
* //returns the color of the pixel at (0, 0) on canvas
* get(0, 0, 20, 20)
* //returns the ImageData object for (0, 0) with dimensions 20px by 20px
* get(canvas, 0, 0, 20, 20)
* //returns the ImageData object for (0, 0) with dimensions 20px by 20px on canvas
**/
function get (...args) {
const [x, y, w, h, src] = args
switch (args.length) {
case 0:
return get(0, 0, width, height)
break
case 2:
data = ctx.getImageData(x, y, 1, 1).data
return color(data[0], data[1], data[2], data[3])
break
case 3: {
const canvas = new OffscreenCanvas(w.width, w.height)
const ctx = canvas.getContext("2d")
if (w instanceof HTMLImageElement) {
ctx.drawImage(w, 0, 0)
data = ctx.getImageData(x, y, 1, 1)
} else {
data = w.getContext("2d").getImageData(x, y, 1, 1).data
}
return color(data[0], data[1], data[2], data[3])
}
break
case 4:
const imageCanvas = new OffscreenCanvas(w, h)
const context = imageCanvas.getContext("2d")
context.putImageData(ctx.getImageData(x, y, w, h), 0, 0)
return imageCanvas
break
case 5: {
const canvas = new OffscreenCanvas(src.width, src.height)
const ctx = canvas.getContext("2d")
ctx.drawImage(src, -x, -y)
return canvas
}
}
}
/**
* masks the previous graphics over the followin' graphics
* @example
* set(width, height)
* clear()
* //masking shape
* mask()
* //shapes to be masked
* const img = get(0, 0, width, height)
* set(document.getElementsByTagName("canvas")[0])
* image(img, 0, 0)
**/
function mask () {
ctx.globalCompositeOperation = "source-atop"
}
// event handlers
mouseReleased = () => {}
mouseScrolled = () => {}
mouseClicked = () => {}
mouseOut = () => {}
mouseOver = () => {}
mouseMoved = () => {}
keyPressed = () => {}
keyReleased = () => {}
keyTyped = () => {}
mouseIsPressed = false
mouseButton = LEFT_BUTTON
mouseX = 0
mouseY = 0
pmouseX = mouseX
pmouseY = mouseY
/**
* Attaches event handlers to the current canvas
*/
function adoptCanvas() {
// xxx HS16 - Bind handlers ONLY to the canvas, so a ski.js
// program can be hosted on a website that needs scrolling.
canvas.tabIndex = -1
canvas.onmousedown = e => {
mousePressed(e)
mouseIsPressed = true
mouseButton = e.button
}
canvas.onmousemove = e => {
const rect = canvas.getBoundingClientRect()
pmouseX = mouseX
pmouseY = mouseY
mouseX = constrain(e.pageX - rect.x, 0, width)
mouseY = constrain(e.pageY - rect.y, 0, height)
mouseMoved(e)
}
canvas.onmouseup = e => {
mouseReleased(e)
mouseClicked(e)
mouseButton = e.button
mouseIsPressed = false
e.preventDefault()
}
canvas.oncontextmenu = e => e.preventDefault()
canvas.onmouseover = e => mouseOver(e)
canvas.onmouseout = e => mouseOut(e)
canvas.onwheel = e => {
mouseScrolled(e)
e.preventDefault()
}
canvas.onkeydown = e => {
e.preventDefault()
key = e.key
keyCode = e.keyCode
keyIsPressed = true
keyPressed(e)
}
canvas.onkeyup = e => {
e.preventDefault()
key = e.key
keyCode = e.keyCode
keyReleased(e)
}
canvas.onkeypress = e => {
e.preventDefault()
key = e.key
keyCode = e.keyCode
keyTyped(e)
}
}
/**
* Removes all event listeners from a canvas, in anticipation
* of a new host.
*/
function rejectCanvas() {
if (!canvas) return;
canvas.onmousedown = null
canvas.onmousemove = null
canvas.onmouseup = null
canvas.oncontextmenu = null
canvas.onmouseover = null
canvas.onmouseout = null
canvas.onwheel = null
canvas.onkeydown = null
canvas.onkeyup = null
canvas.onkeypress = null
}
// data used by ski.js
skiJSData = {
//canvas-related
rect: CORNER,
ellipse: CENTER,
arc: CENTER,
image: CORNER,
leading: 0,
height: 12,
flags: [],
fontString(font, size) {
let flags = ""
if(this.flags.includes("bold")) flags += "bold "
if(this.flags.includes("italics")) flags += "italics "
return (flags + `${size}px ` + font)
},
pos(type, x, y, w, h) {
return type === "rect" || type === "image" ? this[type] < 1 ? [x, y] : [x - w / 2, y - h / 2] : this[type] < 1 ? [x + w / 2, y + w / 2] : [x, y]
},
matrixToArray(matrix) {
return ["a", "b", "c", "d", "e", "f"].map(el => matrix[el])
},
matrices: [],
path: [],
//non-canvas related
rate: 60,
millis: 0,
start: 0,
draw: 0,
angle: DEGREES,
color: RGBA,
}
// FPS
fps = 60
// miscellaneous
/**
* alias for console.debug
* @param {...*} args
*
**/
function debug (...args) {
console.debug(...args)
}
/**
* alias for console.assert
* @param {...*} args
**/
function isEqual (...args) {
console.assert(...args)
}
/**
* returns the day
* @returns {number} - day
**/
function day () {
return (new Date).getDate()
}
/**
* returns the month
* @returns {number} - month
**/
function month () {
return (new Date).getMonth()
}
/**
* returns the year
* @returns {number} - year
**/
function year () {
return (new Date).getYear()
}
/**
* returns the hours
* @returns {number} - hours
**/
function hour () {
return (new Date).getHours()
}
/**
* returns the minutes
* @returns {number} - minutes
**/
function minute () {
return (new Date).getMinutes()
}
/**
* returns the seconds
* @returns {number} - seconds
**/
function seconds () {
return (new Date).getSeconds()
}
/**
* enables the context menu, so you can right-click an' save the canvas as an image.
**/
function enableContextMenu () {
canvas.oncontextmenu = true
}
/**
* alias for document.body.style.cursor
* @param {string} name - name of the cursor
**/
function cursor (name) {
document.body.style.cursor = name
}
/**
* enables image smoothing
**/
function smooth () {
ctx.imageSmoothingEnabled = true
ctx.imageSmoothingQuality = "high"
}
/**
* disables image smoothing
**/
function noSmooth () {
ctx.imageSmoothingEnabled = false
ctx.imageSmoothingQuality = "low"
}
/**
* disables the draw function
**/
function noLoop () {
skiJSData.draw = draw
draw = 0
}
/**
* enables the draw function
**/
function loop () {
draw = skiJSData.draw || draw
}
// math
/**
* returns the maximum value from two values
* does not find the maximum of all values for efficiency's sake
* if such a function is necessary, this will do in a pinch:
* const maxAll = (...args) => args.reduce((a, b) => max(a, b), 0)
* @param {number} a
* @param {number} b
* @return {number} - the maximum
**/
function max (a, b) {
return a > b ? a : b
}
/**
* returns the minimum value from two values
* does not find the minimum of all values for efficiency's sake
* if such a function is necessary, this will do in a pinch:
* const minAll = (...args) => args.reduce((a, b) => min(a, b), 0)
* @param {number} a
* @param {number} b
* @return {number} - the minimum
**/
function min (a, b) {
return a < b ? a : b
}
/**
* returns the magnitude of two values
* @param {number} a
* @param {number} b
* @returns {number} - the magnitude
**/
function mag (a, b) {
return Math.sqrt((a ** 2) + (b ** 2))
}
/**
* returns the euclidean distance between two coordinates
* @param {number} x1
* @param {number} y1