-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcanvas.js
5666 lines (4732 loc) · 152 KB
/
canvas.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
/**
* @copyright Copyright (C) 2019 - 2024 Dorian Thivolle All rights reserved.
* @license GNU General Public License version 3 or later; see LICENSE.txt
* @author Dorian Thivolle
* @name canvas
* @package NoxFly/canvas
* @see https://github.com/NoxFly/canvas
* @since 30 Dec 2019
* @version {1.6.10}
*/
/**
* @vars CANVAS PUBLIC VARS
* read-only, do not modify it
*/
/** @type {CanvasRenderingContext2D} */
let ctx = null;
/** @type {HTMLCanvasElement} */
let canvas = null;
let width = 0,
height = 0,
mouseX = 0,
mouseY = 0,
fps = 60;
/** @type {{ x: number, y: number }} */
let dragPoint = null;
/** @type {Uint8ClampedArray} */
var pixels = undefined;
/**
* Returns the current document's width in pixel
* @return {number} document's width
*/
const documentWidth = () => document.documentElement.clientWidth;
/**
* Returns the current document's height in pixel
* @return {number} document's height
*/
const documentHeight = () => document.documentElement.clientHeight;
// the minimum between document width & document height
let MIN_DOC_SIZE;
// PI
const PI = Math.PI;
// object of boolean
// either it's a mobile or not, in ios or android
const isDevice = Object.freeze({
mobile: /iPhone|iPad|iPod|Android/i.test(navigator.userAgent),
ios: /iPad|iPhone|iPod/.test(navigator.userAgent),
android: /Android/.test(navigator.userAgent)
});
// mouse direction - can't be a vector class instance, just a basic object {x, y}
const mouseDirection = { x: 0, y: 0 };
/**
* Begins a new sub-path at the point specified by the given (x, y) coordinates.
* @param {number} x The x-axis (horizontal) coordinate of the point.
* @param {number} y The y-axis (vertical) coordinate of the point.
* @example
* moveTo(0, 0)
*/
const moveTo = (x, y) => ctx.moveTo(x, y);
/**
* Adds a straight line to the current sub-path by connecting the sub-path's last point to the specified (x, y) coordinates.
* @param {number} x The x-axis coordinate of the line's end point.
* @param {number} y The y-axis coordinate of the line's end point.
* @example
* lineTo(10, 50)
*/
const lineTo = (x, y) => ctx.lineTo(x, y);
/**
* Adds a circular arc to the current sub-path, using the given control points and radius.
* The arc is automatically connected to the path's latest point with a straight line, if necessary for the specified parameters.
* @param {number} x1 The x-axis coordinate of the first control point.
* @param {number} y1 The y-axis coordinate of the first control point.
* @param {number} x2 The x-axis coordinate of the second control point.
* @param {number} y2 The y-axis coordinate of the second control point.
* @param {number} r The arc's radius. Must be non-negative.
* @example
* arcTo(200, 130, 50, 20, 40)
*/
const arcTo = (x1, y1, x2, y2, r) => ctx.arcTo(x1 , y1, x2, y2, r);
/**
* Adds a line from p1(x1, y1) to p2(x2, y2) to the current sub-path.
* @param {number} x1 The x-axis coordinate of the first point.
* @param {number} y1 The y-axis coordinate of the first point.
* @param {number} x2 The x-axis coordinate of the second point.
* @param {number} y2 The y-axis coordinate of the second point.
* @example
* line(10, 40, 100, 150)
*/
const line = (x1, y1, x2, y2) => {
beginPath();
moveTo(x1 - NOX_PV.offsetLineBlur, y1 - NOX_PV.offsetLineBlur);
lineTo(x2 - NOX_PV.offsetLineBlur, y2 - NOX_PV.offsetLineBlur);
closePath();
if(NOX_PV.bStroke)
ctx.stroke();
};
/**
* Adds a polyline with given arguments to the current sub-path.
* It goes by pairs (x, y), so an even number of arguments.
* @argument {number[]} values Array of point's positions. Need to be even number
* @example
* polyline(0, 0, 10, 10, 100, 50)
*/
const polyline = (...values) => {
// got an odd number of argument
if(values.length % 2 !== 0) {
throw new Error('The function polyline must take an even number of values');
}
beginPath();
if(values.length > 0) {
moveTo(values[0], values[1]);
}
for(let i=2; i < values.length; i += 2) {
const x = values[i],
y = values[i+1];
lineTo(x, y);
}
if(NOX_PV.bStroke)
ctx.stroke();
if(NOX_PV.bFill)
ctx.fill();
};
/**
* Adds a circular arc to the current sub-path.
* @param {number} x The horizontal coordinate of the arc's center.
* @param {number} y The vertical coordinate of the arc's center.
* @param {number} r The arc's radius. Must be positive.
* @param {number} start The angle at which the arc starts in radians, measured from the positive x-axis.
* @param {number} end The angle at which the arc ends in radians, measured from the positive x-axis.
* @param {boolean} antiClockwise An optional boolean. If true, draws the arc counter-clockwise between the start and end angles. The default is false (clockwise).
* @example
* arc(100, 70, 20)
*/
const arc = (x, y, r, start, end, antiClockwise=false) => {
beginPath();
ctx.arc(x, y, r, start, end, antiClockwise);
closePath();
if(NOX_PV.bStroke)
ctx.stroke();
if(NOX_PV.bFill)
ctx.fill();
};
/**
* Adds a circle to the current sub-path
* @param {number} x circle's X
* @param {number} y circle's y
* @param {number} r circle's radius. Must be positive.
* @example
* circle(70, 70, 15)
*/
const circle = (x, y, r) => {
arc(x, y, r, 0, 2 * PI);
};
/**
* Draws a rectangle that is filled according to the current fillStyle.
* This method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it.
* @param {number} x rectangle's X (top-left corner)
* @param {number} y rectangle's Y (top-left corner)
* @param {number} w rectangle's width. Negative values will draw rectangle to the left.
* @param {number} h rectangle's height. Negative values will draw rectangle to the up.
* @example
* fillRect(0, 0, 100, 150)
*/
const fillRect = (x, y, w, h) => {
ctx.fillRect(x, y, w, h);
};
/**
* Draws a rectangle that is stroked (outlined) according to the current strokeStyle and other context settings.
* This method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it.
* @param {number} x rectangle's X (top-left corner)
* @param {number} y rectangle's Y (top-left corner)
* @param {number} w rectangle's width. Negative values will draw rectangle to the left.
* @param {number} h rectangle's height. Negative values will draw rectangle to the up.
* @example
* strokeRect(0, 0, 100, 150)
*/
const strokeRect = (x, y, w, h) => {
ctx.strokeRect(x, y, w, h);
};
/**
* Adds a rectangle to the current path.
* @param {number} x rectangle's X (top-left corner)
* @param {number} y rectangle's Y (top-left corner)
* @param {number} w rectangle's Width
* @param {number} h rectangle's height
* @example
* rect(0, 0, 100, 150)
*/
const rect = (x, y, w, h) => {
ctx.rect(x, y, w, h);
if(NOX_PV.bFill)
ctx.fill();
if(NOX_PV.bStroke)
ctx.stroke();
};
/**
* Draws a rounded rectangle
* @param {number} x The X-Axis rounded rectangle's position
* @param {number} y The Y-Axis rounded rectangle's position
* @param {number} w The width of the rounded rectangle
* @param {number} h The height of the rounded rectangle
* @param {number} radius top-left corner's radius or 4 corners radius if this is the only one passed
* @param {number} radiusTR top-right corner's radius
* @param {number} radiusBR bottom-right corner's radius
* @param {number} radiusBL bottom-left corner's radius
*/
const roundRect = (x=0, y=0, w=0, h=0, radius=0, radiusTR, radiusBR, radiusBL) => {
if(radiusTR === undefined) radiusTR = radius;
if(radiusBR === undefined) radiusBR = radius;
if(radiusBL === undefined) radiusBL = radius;
radius = min(max(0, radius), 50);
radiusTR = min(max(0, radiusTR), 50);
radiusBR = min(max(0, radiusBR), 50);
radiusBL = min(max(0, radiusBL), 50);
const x1 = x + radius,
y1 = y;
const x2 = x + w - radiusTR,
y2 = y;
const x3 = x + w,
y3 = y + h - radiusBR;
const x4 = x + radiusBL,
y4 = y + h;
const x5 = x,
y5 = y + radius;
beginPath();
moveTo(x1, y1);
lineTo(x2, y2);
arcTo(x2 + radiusTR, y2, x2 + radiusTR, y2 + radiusTR, radiusTR);
lineTo(x3, y3);
arcTo(x3, y3 + radiusBR, x3 - radiusBR, y3 + radiusBR, radiusBR);
lineTo(x4, y4);
arcTo(x4 - radiusBL, y4, x, y4 - radiusBL, radiusBL);
lineTo(x5, y5);
arcTo(x5, y5 - radius, x1, y1, radius);
closePath();
if(NOX_PV.bStroke)
ctx.stroke();
if(NOX_PV.bFill)
ctx.fill();
};
/**
* Create a custom path with assembly of shapes.
* It's the same use as the <path> tag for SVG.
* It adds the path to the current one.
* Instructions : M, L, H, V, A, Z
* @param {string} p path string that will be converted to d path code
* @example
* p('M0 0 L 10 10 A 20 20 H 50 V 50 l 20 20 Z')
*/
const path = p => {
// instruction: letter (MLHVAZ)
// argument: numbers
// remove spaces at the start and the end of the string
p = p.trim();
// a path must start with a moveTo instruction
if(!p.startsWith('M')) {
return;
}
// split each instructions / arguments
p = p.split(' ');
// default starting mode is moveTo to positionate the cursor
// remove a loop in the for loop
let mode = 'M';
// availible modes with number of arguments that is needed
const modes = {
M: {
n: 2,
f: (x, y) => moveTo(x, y)
},
L: {
n: 2,
f: (x, y) => lineTo(x, y)
},
H: {
n: 1,
f: (x, y) => lineTo(x, y)
},
V: {
n: 1,
f: (y, x) => lineTo(x, y)
},
A: {
n: 6,
f: (x, y, r, start, end, antiClockwise) => ctx.arc(x, y, r, radian(start), radian(end), antiClockwise === 1)
},
Z: {
n: 0,
f: () => lineTo(parseFloat(p[1]), parseFloat(p[2]))
}
};
// regex to verify if each point is okay
const reg = new RegExp(`^[${Object.keys(modes).join('')}]|(\-?\d+(\.\d+)?)$`, 'i');
// if a point isn't well written, then stop
if(p.filter(point => reg.test(point)).length === 0) {
return;
}
// doesn't need to try to draw something: need at least an instruction M first and 2 parameters x,y
if(p.length < 3) {
return;
}
// code translated path
const d = [];
// number of points - 1: last index of the array of points
const lastIdx = p.length - 1;
// read arguments - normally starts with x,y of the M instruction
for(let i=0; i < p.length; i++) {
const point = p[i];
// is a letter - new instruction
if(/[a-z]/i.test(point)) {
// lowercase - relative
// uppercase - absolute
// push pile of instructions (only 2 saved)
mode = point;
// if the instruction is Z
if(mode === 'Z') {
// and if it's the last mode
if(i === lastIdx) {
// then close the path
d.push('Z');
} else {
// cannot use the Z somewhere else than the last point
return;
}
}
// lowercase Z isn't recognized
if(['z'].includes(mode)) {
return;
}
const nArg = modes[mode.toUpperCase()].n;
// depending on the current instruction, there need to have to right number of argument following this instruction
if(lastIdx - nArg < i) {
return;
}
//
const lastPos = { x: 0, y: 0 };
// get the last cursor position
if(d.length > 0) {
const prev = d[d.length - 1];
const hv = ['H', 'V'].indexOf(prev[0]);
if(hv !== -1) {
lastPos.x = prev[1+hv]; // x of the last point
lastPos.y = prev[2-hv]; // y of the last point
}
else {
const k = 1;
lastPos.x = prev[k]; // x of the last point
lastPos.y = prev[k+1]; // y of the last point
}
}
// array that is refresh every instruction + argument given
const arr = [mode.toUpperCase()];
// if it's H or V instruction, keep the last X or Y
const hv = ['H', 'V'].indexOf(arr[0]);
// add each argument that are following the instruction
for(let j=0; j < nArg; j++) {
i++;
const n = parseFloat(p[i]);
// it must be a number
if(isNaN(n)) {
return;
}
// push the treated argument
arr.push(n);
}
// only for H or V
if(hv !== -1) {
arr.push(lastPos[Object.keys(lastPos)[1-hv]]);
}
if(arr[0] === 'A') {
arr[1] -= arr[3];
}
// lowercase: relative to last point - only for MLHVA
if(/[mlhva]/.test(mode)) {
if(mode === 'v') {
arr[1] += lastPos.y;
}
else if(mode === 'h') {
arr[1] += lastPos.x;
}
else {
arr[1] += lastPos.x;
arr[2] += lastPos.y;
}
}
// add the instruction and its arguments to the translated path
d.push(arr);
// draw the arc isn't enough, we have to move the cursor to the end of the arc too
if(arr[0] === 'A') {
// arr = ['A', x, y, r, start, end, acw]
const angle = radian(arr[5]);
const x = arr[1] + cos(angle) * arr[3]
y = arr[2] + sin(angle) * arr[3];
d.push(['M', x, y]);
}
}
}
// start draw depending on what's written
beginPath();
d.forEach(step => {
// surely Z()
if(typeof step === 'string') {
modes[step].f();
}
// else it's MLHVA with position arguments
else {
modes[step[0]].f(...step.slice(1));
}
});
if(NOX_PV.bFill)
ctx.fill();
if(NOX_PV.bStroke)
ctx.stroke();
}
/**
* Adds a text to the current sub-path
* @param {string} txt text to be displayed
* @param {number} x text's X position
* @param {number} y text's Y position
* @example
* text('Hello world', 20, 20)
*/
const text = (txt, x=0, y=0) => {
// multiple lines
if(/\n/.test(txt)) {
const size = parseInt(NOX_PV.fontSize.replace(/(\d+)(\w+)?/, '$1'));
txt = txt.split('\n');
for(let i=0; i < txt.length; i++) {
ctx.fillText(txt[i], x, y + i * size);
}
}
// one line
else {
ctx.fillText(txt, x, y);
}
};
/**
* Text settings - sets the size and the font-family
* @param {number} size font size
* @param {string} font font name
* @example
* setFont(15, 'Monospace')
*/
const setFont = (size, font) => {
ctx.font = `${size}px ${font}`;
NOX_PV.fontSize = `${size}px`;
NOX_PV.fontFamily = font;
};
/**
* Sets the font size of the text
* @param {number} size font size
* @example
* fontSize(20)
*/
const fontSize = size => {
ctx.font = `${size}px ${NOX_PV.fontFamily}`;
NOX_PV.fontSize = `${size}px`;
};
/**
* Sets the font-family of the text
* @param {string} font font-family
* @example
* fontFamily('Monospace')
*/
const fontFamily = font => {
ctx.font = `${NOX_PV.fontSize} ${font}`;
NOX_PV.fontFamily = font;
};
/**
* Change the text's alignement
* @param {CanvasTextAlign} alignment text's alignment
* @example
* alignText('center')
*/
const alignText = alignment => {
ctx.textAlign = (['left', 'right', 'center', 'start', 'end'].indexOf(alignment) > -1) ? alignment : 'left';
};
/**
* Adds a cubic Bézier curve to the current sub-path.
* It requires three points: the first two are control points and the third one is the end point.
* The starting point is the latest point in the current path, which can be changed using moveTo() before creating the Bézier curve.
* @param {number} cp1x The x-axis coordinate of the first control point.
* @param {number} cp1y The y-axis coordinate of the first control point.
* @param {number} cp2x The x-axis coordinate of the second control point.
* @param {number} cp2y The y-axis coordinate of the second control point.
* @param {number} x The x-axis coordinate of the end point.
* @param {number} y The y-axis coordinate of the end point.
* @example
* moveTo(50, 20)
* bezierCurveTo(230, 30, 150, 80, 250, 100)
*/
const bezierCurveTo = (cp1x, cp1y, cp2x, cp2y, x, y) => {
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
};
/**
* Adds a quadratic Bézier curve to the current sub-path.
* It requires two points: the first one is a control point and the second one is the end point.
* The starting point is the latest point in the current path, which can be changed using moveTo() before creating the quadratic Bézier curve.
* @param {number} cpx The x-axis coordinate of the control point.
* @param {number} cpy The y-axis coordinate of the control point.
* @param {number} x The x-axis coordinate of the end point.
* @param {number} y The y-axis coordinate of the end point.
* @example
* moveTo(50, 20)
* quadraticCurveTo(230, 30, 50, 100)
*/
const quadraticCurveTo = (cpx, cpy, x, y) => {
ctx.quadraticCurveTo(cpx, cpy, x, y);
};
/**
* Applies a shadow to the shape that needs to be drawn.
* @param {*} shadowColor The shadow's color
* @param {number} shadowBlur The shadow's blur. Can be used for glow effect
* @param {number} shadowOffsetX The shadow X-Axis offset
* @param {number} shadowOffsetY The shadow Y-Axis offset
*/
const setShadow = (shadowColor, shadowBlur=0, shadowOffsetX=0, shadowOffsetY=0) => {
ctx.shadowColor = NOX_PV.colorTreatment(shadowColor);
ctx.shadowBlur = shadowBlur;
ctx.shadowOffsetX = shadowOffsetX;
ctx.shadowOffsetY = shadowOffsetY;
};
/**
* Removes the shadow settings if there's any.
*/
const removeShadow = () => {
ctx.shadowColor = "rgba(0, 0, 0, 0)";
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
};
/**
* Saves the entire state of the canvas by pushing the current state onto a stack.
* The drawing state that gets saved onto a stack consists of:
* - The current transformation matrix.
* - The current clipping region.
* - The current dash list.
* - The current values of the following attributes:
* strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset,
* shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign,
* textBaseline, direction, imageSmoothingEnabled.
* @example
* push()
*/
const push = () => ctx.save();
/**
* restores the most recently saved canvas state by popping the top entry in the drawing state stack.
* If there is no saved state, this method does nothing.
* @example
* pop()
*/
const pop = () => ctx.restore();
/**
* Adds a translation transformation to the current matrix.
* @param {number} x Distance to move in the horizontal direction. Positive values are to the right, and negative to the left.
* @param {number} y Distance to move in the vertical direction. Positive values are down, and negative are up.
* @example
* translate(100, 200)
*/
const translate = (x, y) => ctx.translate(x, y);
/**
* Adds a rotation to the transformation matrix.
* @param {number} degree The rotation angle, clockwise in degree. You can use radian(deg) to calculate a radian from a degree.
* @example
* rotate(45) // rotates 45 degrees
*/
const rotate = degree => ctx.rotate(radian(-degree));
/**
* turns the current or given path into the current clipping region.
* The previous clipping region, if any, is intersected with the current or given path to create the new clipping region.
* @param {Path2D} path A Path2D path to use as the clipping region.
* @param {string} fillRule The algorithm by which to determine if a point is inside or outside the clipping region. Possible values:
* - 'nonzero': The non-zero winding rule. Default rule.
* - 'evenodd': The even-odd winding rule.
* @example
* // Create circular clipping region
* beginPath();
* arc(100, 75, 50, 0, PI * 2);
* clip();
* // Draw stuff that gets clipped
* fill('blue');
* fillRect(0, 0, width, height);
* fill('orange');
* fillRect(0, 0, 100, 100);
*/
const clip = (...args) => ctx.clip(...args);
/**
* Adds a scaling transformation to the canvas units horizontally and/or vertically.
* @param {number} x Scaling factor in the horizontal direction. A negative value flips pixels across the vertical axis. A value of 1 results in no horizontal scaling.
* @param {number} y Scaling factor in the vertical direction. A negative value flips pixels across the horizontal axis. A value of 1 results in no vertical scaling.
*/
const scale = (x, y=x) => ctx.scale(x, y);
/**
* Says to not fill next hapes
*/
const noFill = () => {
NOX_PV.bFill = false;
};
/**
* Says to not stroke next shapes
*/
const noStroke = () => {
NOX_PV.bStroke = false;
};
/**
* Changes the canvas color
* @param {...any} color background color
*/
const background = (...color) => {
canvas.style.backgroundColor = NOX_PV.colorTreatment(...color);
};
/**
* Sets the stroke color for next shapes to draw
* @param {...any} color Stroke color
*/
const stroke = (...color) => {
ctx.strokeStyle = NOX_PV.colorTreatment(...color);
NOX_PV.bStroke = true;
};
/**
* Sets the strokeweight for next shapes to draw
* @param {number} weight weight of the stroke
*/
const strokeWeight = weight => {
ctx.lineWidth = weight;
NOX_PV.offsetLineBlur = (weight % 2 === 0)? 0 : 0.5;
};
/**
* Set the linecap style
* @param {CanvasLineCap} style linecap style
*/
const linecap = style => {
ctx.lineCap = ['butt', 'round', 'square'].indexOf(style) > -1 ? style : 'butt';
};
/**
* Set the fill color for shapes to draw
* @param {...any} color Fill color
*/
const fill = (...color) => {
ctx.fillStyle = NOX_PV.colorTreatment(...color);
NOX_PV.bFill = true;
};
/**
* Creates a gradient along the line connecting two given coordinates.
* @param {number} x1 The x-axis coordinate of the start point.
* @param {number} y1 The y-axis coordinate of the start point.
* @param {number} x2 The x-axis coordinate of the end point.
* @param {number} y2 The y-axis coordinate of the end point.
* @return {CanvasGradient} A linear CanvasGradient initialized with the specified line.
*/
const createLinearGradient = (x1, y1, x2, y2) => ctx.createLinearGradient(x1, y1, x2, y2);
/**
* Creates a gradient along the line connecting two given coordinates.
* Fills the gradient with given values. It's to merge createLinearGradient() and gradient.addColorStop() in one function.
* @param {number} x1 The x-axis coordinate of the start point.
* @param {number} y1 The y-axis coordinate of the start point.
* @param {number} x2 The x-axis coordinate of the end point.
* @param {number} y2 The y-axis coordinate of the end point.
* @param {(offset:number, color:string)} params The color parameters. It has to be as pair : offset (between 0 & 1), and color
* @return {CanvasGradient} A linear CanvasGradient initialized with the specified line and colors.
* @example
* makeLinearGradient(0, 0, width, height, 0, 'black', 1, 'white')
*/
const makeLinearGradient = (x1, y1, x2, y2, ...params) => {
if(params.length % 2 !== 0) {
throw new Error('you have to tell params by pair (offset, color). Odd number of arguments given.');
}
const grad = createLinearGradient(x1, y1, x2, y2);
for(let i=0; i < params.length; i += 2) {
const offset = params[i];
const color = NOX_PV.colorTreatment(params[i + 1]);
grad.addColorStop(offset, color);
}
return grad;
};
/**
* Clears the canvas from x,y to x+w;y+h
* Erases the pixels in a rectangular area.
* @param {number} x The x-axis coordinate of the rectangle's starting point.
* @param {number} y The y-axis coordinate of the rectangle's starting point.
* @param {number} w The rectangle's width. Positive values are to the right, and negative to the left.
* @param {number} h The rectangle's height. Positive values are down, and negative are up.
* @example
* clearRect(0, 0, width, height)
*/
const clearRect = (x, y, w, h) => ctx.clearRect(x, y, w, h);
/**
* starts a new path by emptying the list of sub-paths.
* Call this method when you want to create a new path.
* @example
* beginPath()
*/
const beginPath = () => ctx.beginPath();
/**
* attempts to add a straight line from the current point to the start of the current sub-path.
* If the shape has already been closed or has only one point, this function does nothing.
* @example
* closePath()
*/
const closePath = () => ctx.closePath();
/**
* Draws a focus ring around the current or given path, if the specified element is focused.
* @param {Element|Path2D} elementOrPath2D A Path2D path to use.
* @param {Element} element The element to check whether it is focused or not.
* @example
* drawFocusIfNeeded(button1)
*/
const drawFocusIfNeeded = (elementOrPath2D, element = null) => {
if(element === null && !(elementOrPath2D instanceof Path2D)) {
ctx.drawFocusIfNeeded(elementOrPath2D);
} else {
ctx.drawFocusIfNeeded(elementOrPath2D, element);
}
};
/**
* Sets line dashes to current path
* @param {Array} array line dash to set to the current path
* @example
* setLineDash([5, 15])
*/
const setLineDash = array => {
if(!Array.isArray(array)) {
throw new Error('Array type expected. Got ' + typeof array);
}
ctx.setLineDash(array);
};
/**
* Returns the ctx.getLineDash() function's value
* @return {Array} An Array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units).
* If the number, when setting the elements, is odd, the elements of the array get copied and concatenated.
* For example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25].
* console.info(getLineDash())
*/
const getLineDash = () => ctx.getLineDash();
/**
* Specifies the alpha (transparency) value that is applied to shapes and images before they are drawn onto the canvas.
* @param {number} globalAlpha A number between 0.0 (fully transparent) and 1.0 (fully opaque), inclusive. The default value is 1.0.
* Values outside that range, including Infinity and NaN, will not be set, and globalAlpha will retain its previous value.
* @example
* globalAlpha(0.5)
*/
const globalAlpha = globalAlpha => {
ctx.globalAlpha = globalAlpha;
};
/**
* Sets the type of compositing operation to apply when drawing new shapes.
* @param {GlobalCompositeOperation} type a string identifying which of the compositing or blending mode operations to use.
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation for more details
* @example
* globalCompositeOperation('soft-light')
*/
const globalCompositeOperation = type => {
ctx.globalCompositeOperation = type;
}
/**
* Sets the image smoothing quality
* @param {ImageSmoothingQuality} quality smooth quality
* @example
* setSmoothingQuality('low')
*/
const setSmoothingQuality = quality => {
ctx.imageSmoothingQuality = quality;
};
/**
* Reports whether or not the specified point is contained in the current path.
* @param {number|Path2D} x either x point coordinate or path2D. unaffected by the current transformation of the context. If path is unspecified, current path is used.
* @param {number} y either x or y point coordinate, following the 1st argument's type. unaffected by the current transformation of the context.
* @param {CanvasFillRule} fillRule The algorithm by which to determine if a point is inside or outside the path. 'nonzero' (default) or 'evenodd'
* @return {boolean} A boolean, which is true if the specified point is contained in the current or specified path, otherwise false.
* @example
* if(isPointInPath(30, 20)) {
* // ... do stuff
* }
*/
const isPointInPath = function(x, y, fillRule='nonzero') {
return ctx.isPointInPath(...arguments);
};
/**
* Reports whether or not the specified point is inside the area contained by the stroking of a path.
* @param {number|Path2D} x The x-axis coordinate of the point to check. (or Path2D)
* @param {number} y The y-axis coordinate of the point to check.
* @return {boolean} A boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false.
* @example
* if(isPointInStroke(30, 40)) {
* // ... do stuff
* }
*/
const isPointInStroke = function(x, y) {
return ctx.isPointInStroke(...arguments);
};
/**
* Retrieves the current transformation matrix being applied to the context.
* @return {DOMMatrix} A DOMMatrix object.
* @example
* const transformMatrix = getTransform()
*/
const getTransform = () => ctx.getTransform();
/**
* Sets the line dash offset.
* @param {number} value A float specifying the amount of the line dash offset. The default value is 0.0.
* @example
* lineDashOffset(1)
*/
const lineDashOffset = (value=0.0) => {
ctx.lineDashOffset = value;
};
/**