-
Notifications
You must be signed in to change notification settings - Fork 183
/
Canvas.ts
1289 lines (1049 loc) · 46.9 KB
/
Canvas.ts
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
/*! Pts.js is licensed under Apache License 2.0. Copyright © 2017-current William Ngan and contributors. (https://github.com/williamngan/pts) */
import {MultiTouchSpace} from './Space';
import {VisualForm, Font} from "./Form";
import {Pt, Group, Bound} from "./Pt";
import {Const, Util} from "./Util";
import {Typography as Typo} from "./Typography";
import { Rectangle } from './Op';
import {Img} from './Image';
import {PtLike, GroupLike, RenderingContext2D, DefaultFormStyle, PtLikeIterable, PtIterable, CanvasSpaceOptions} from "./Types";
/**
* CanvasSpace is an implementation of the abstract class [`Space`](#link). It represents a space for HTML Canvas.
* Learn more about the concept of Space in [this guide](../guide/Space-0500.html).
*/
export class CanvasSpace extends MultiTouchSpace {
protected _canvas:HTMLCanvasElement;
protected _container:Element;
protected _pixelScale = 1;
protected _bgcolor = "#e1e9f0";
protected _ctx:CanvasRenderingContext2D;
protected _offscreen = false;
protected _offCanvas:HTMLCanvasElement;
protected _offCtx:RenderingContext2D;
protected _resizeObserver:ResizeObserver;
protected _autoResize = true;
protected _initialResize = false;
/**
* Create a CanvasSpace which represents a HTML Canvas Space
* @param elem Specify an element by its "id" attribute as string, or by the element object itself. An element can be an existing `<canvas>`, or a `<div>` container in which a new `<canvas>` will be created. If left empty, a `<div id="pt_container"><canvas id="pt" /></div>` will be added to DOM. Use css to customize its appearance if needed.
* @param callback an optional callback `function(boundingBox, spaceElement)` to be called when canvas is appended and ready. Alternatively, a "ready" event will also be fired from the `<canvas>` element when it's appended, which can be traced with `spaceInstance.canvas.addEventListener("ready")`
* @example `new CanvasSpace( "#myElementID" )`
*/
constructor( elem:string | Element, callback?:Function ) {
super();
let _selector:Element = null;
let _existed = false;
this.id = Util.uniqueId();
// get selector element depending on whether `elem` is an element id string or an element object
if ( elem instanceof Element ) {
_selector = elem;
this.id = _selector.id || this.id;
} else {
let id = <string>elem;
id = ( elem[0] === "#" || elem[0] === "." ) ? elem : "#" + elem;
_selector = document.querySelector( id );
this.id = id.substr( 1 );
}
// if selector is not defined, create a default canvas
if ( !_selector ) {
this._container = this._createElement( "div", this.id + "_container" );
this._canvas = this._createElement( "canvas", this.id ) as HTMLCanvasElement;
document.body.appendChild( this._container );
// if selector is element but not canvas, create a canvas inside it
} else if ( _selector.nodeName.toLowerCase() != "canvas" ) {
this._container = _selector;
this._canvas = this._createElement( "canvas", this.id + "_canvas" ) as HTMLCanvasElement;
this._initialResize = true;
// if selector is an existing canvas
} else {
this._canvas = _selector as HTMLCanvasElement;
this._container = _selector.parentElement;
this._autoResize = false;
_existed = true;
}
// store canvas 2d rendering context
this._ctx = this._canvas.getContext( '2d' );
// if we created the canvas, add it to the container and observe mutation for readiness
if ( !_existed ) {
const observer = new MutationObserver( ( mutations ) => {
mutations.forEach( ( mutation ) => {
if ( mutation.type === 'childList' && mutation.addedNodes.length ) {
for ( let node of mutation.addedNodes ) {
if ( node === this._canvas ) {
this._ready( callback );
observer.disconnect();
return;
}
}
}
} );
} );
observer.observe( this._container, { childList: true } );
this._container.appendChild( this._canvas );
} else {
// Wait one turn for .setup() to be called before firing ready event
setTimeout( this._ready.bind( this, callback ), 100 );
}
}
/**
* Helper function to create a DOM element
* @param elem element tag name
* @param id element id attribute
*/
protected _createElement( elem = "div", id ) {
const d = document.createElement( elem );
d.setAttribute( "id", id );
return d;
}
/**
* Handle callbacks after element is mounted in DOM
* @param callback
*/
private _ready( callback:Function ) {
if ( !this._container ) throw new Error( `Cannot initiate #${this.id} element` );
this._isReady = true;
this._resizeHandler( null );
this.clear( this._bgcolor );
this._canvas.dispatchEvent( new Event( "ready" ) );
for ( const k in this.players ) {
if ( this.players.hasOwnProperty( k ) ) {
if ( this.players[k].start ) this.players[k].start( this.bound.clone(), this );
}
}
this._pointer = this.center;
this._initialResize = false; // unset
if ( callback ) callback( this.bound, this._canvas );
}
/**
* Set up various options for CanvasSpace. The `opt` parameter is an object with the following fields. This is usually set during instantiation, eg `new CanvasSpace(...).setup( { opt } )`
* @param opt a [`CanvasSpaceOptions`](#link) object with optional settings, ie `{ bgcolor:string, resize:boolean, retina:boolean, offscreen:boolean, pixelDensity:number }`.
* @example `space.setup({ bgcolor: "#f00", retina: true, resize: true })`
*/
setup( opt:CanvasSpaceOptions ):this {
this._bgcolor = opt.bgcolor ? opt.bgcolor : "transparent";
this.autoResize = ( opt.resize != undefined ) ? opt.resize : false;
if ( opt.retina !== false ) {
const r1 = window ? window.devicePixelRatio || 1 : 1;
this._pixelScale = Math.max( 1, r1 );
}
if ( opt.offscreen ) {
this._offscreen = true;
this._offCanvas = this._createElement( "canvas", this.id + "_offscreen" ) as HTMLCanvasElement;
this._offCtx = this._offCanvas.getContext( '2d' );
} else {
this._offscreen = false;
}
if ( opt.pixelDensity ) {
this._pixelScale = opt.pixelDensity;
}
return this;
}
/**
* Set whether the canvas element should resize when its container is resized.
* @param auto a boolean value indicating if auto size is set
*/
set autoResize( auto ) {
this._autoResize = auto;
if ( auto ) {
this._resizeObserver = new ResizeObserver( entries => {
this._resizeHandler( null );
} );
this._resizeObserver.observe( this._container );
} else {
if ( this._resizeObserver ) this._resizeObserver.disconnect();
}
}
get autoResize(): boolean { return this._autoResize; }
/**
* This overrides Space's `resize` function. It's used as a callback function for window's resize event and not usually called directly. You can keep track of resize events with `resize: (bound ,evt)` callback in your player objects.
* @param b a Bound object to resize to
* @param evt Optionally pass a resize event
* @see Space.add
*/
resize( b:Bound, evt?:Event ):this {
this.bound = b;
this._canvas.width = Math.ceil( this.bound.size.x ) * this._pixelScale;
this._canvas.height = Math.ceil( this.bound.size.y ) * this._pixelScale;
this._canvas.style.width = Math.ceil( this.bound.size.x ) + "px";
this._canvas.style.height = Math.ceil( this.bound.size.y ) + "px";
if ( this._offscreen ) {
this._offCanvas.width = Math.ceil( this.bound.size.x ) * this._pixelScale;
this._offCanvas.height = Math.ceil( this.bound.size.y ) * this._pixelScale;
// this._offCanvas.style.width = Math.floor(this.bound.size.x) + "px";
// this._offCanvas.style.height = Math.floor(this.bound.size.y) + "px";
}
if ( this._pixelScale != 1 ) {
this._ctx.scale( this._pixelScale, this._pixelScale );
if ( this._offscreen ) {
this._offCtx.scale( this._pixelScale, this._pixelScale );
}
}
for ( const k in this.players ) {
if ( this.players.hasOwnProperty( k ) ) {
const p = this.players[k];
if ( p.resize ) p.resize( this.bound, evt );
}
}
this.render( this._ctx );
// if it's a valid resize event and space is not playing, repaint the canvas once
if ( evt && !this.isPlaying ) this.playOnce( 0 );
return this;
}
/**
* Window resize handling
* @param evt
*/
protected _resizeHandler( evt:Event ) {
const b = ( this._autoResize || this._initialResize ) ? this._container.getBoundingClientRect() : this._canvas.getBoundingClientRect();
if ( b ) {
const box = Bound.fromBoundingRect( b );
// Need to compute offset from window scroll. See outerBound calculation in Space's _mouseAction
box.center = box.center.add( window?.scrollX || 0, window?.scrollY || 0 );
this.resize( box, evt );
}
}
/**
* Set a background color for this canvas. Alternatively, you may use `clear()` function.
@param bg background color as hex or rgba string
*/
set background( bg:string ) { this._bgcolor = bg; }
get background():string { return this._bgcolor; }
/**
* `pixelScale` property returns a number that let you determine if the screen is "retina" (when value >= 2)
*/
public get pixelScale():number {
return this._pixelScale;
}
/**
* Check if an offscreen canvas is created
*/
public get hasOffscreen():boolean {
return this._offscreen;
}
/**
* Get the rendering context of offscreen canvas (if created via `setup()`)
*/
public get offscreenCtx():RenderingContext2D { return this._offCtx; }
/**
* Get the offscreen canvas element
*/
public get offscreenCanvas():HTMLCanvasElement { return this._offCanvas; }
/**
* Get a new `CanvasForm` for drawing
* @see `CanvasForm`
*/
public getForm():CanvasForm { return new CanvasForm( this ); }
/**
* Get the html canvas element
*/
get element():HTMLCanvasElement {
return this._canvas;
}
/**
* Get the parent element that contains the canvas element
*/
get parent():Element {
return this._container;
}
/**
* A property to indicate if the Space is ready
*/
get ready():boolean {
return this._isReady;
}
/**
* Get the rendering context of canvas
* @example `form.ctx.clip()`
*/
public get ctx():CanvasRenderingContext2D { return this._ctx; }
/**
* Clear the canvas with its background color. Overrides Space's `clear` function.
* @param bg Optionally specify a custom background color in hex or rgba string, or "transparent". If not defined, it will use its `bgcolor` property as background color to clear the canvas.
*/
clear( bg?:string ):this {
if ( bg ) this._bgcolor = bg;
const lastColor = this._ctx.fillStyle;
const px = Math.ceil( this.pixelScale );
if ( !this._bgcolor || this._bgcolor === "transparent" ) {
this._ctx.clearRect( -px, -px, this._canvas.width + px, this._canvas.height + px );
} else {
// semi-transparent bg needs to be cleared first
if ( this._bgcolor.indexOf( "rgba" ) === 0 || ( this._bgcolor.length === 9 && this._bgcolor.indexOf( "#" ) === 0 ) ) {
this._ctx.clearRect( -px, -px, this._canvas.width + px, this._canvas.height + px );
}
this._ctx.fillStyle = this._bgcolor;
this._ctx.fillRect( -px, -px, this._canvas.width + px, this._canvas.height + px );
}
this._ctx.fillStyle = lastColor;
return this;
}
/**
* Similiar to `clear()` but clear the offscreen canvas instead
* @param bg Optionally specify a custom background color in hex or rgba string, or "transparent". If not defined, it will use its `bgcolor` property as background color to clear the canvas.
*/
clearOffscreen( bg?:string ):this {
if ( this._offscreen ) {
const px = Math.ceil( this.pixelScale );
if ( bg ) {
this._offCtx.fillStyle = bg;
this._offCtx.fillRect( -px, -px, this._canvas.width + px, this._canvas.height + px );
} else {
this._offCtx.clearRect( -px, -px, this._offCanvas.width + px, this._offCanvas.height + px );
}
}
return this;
}
/**
* Main animation function.
* @param time current time
*/
protected playItems( time: number ) {
if ( this._isReady ) {
this._ctx.save();
if ( this._offscreen ) this._offCtx.save();
super.playItems( time );
this._ctx.restore();
if ( this._offscreen ) this._offCtx.restore();
this.render( this._ctx );
}
}
/**
* Dispose of browser resources held by this space and remove all players. Call this before unmounting the canvas.
*/
dispose():this {
// remove event listeners
this._resizeObserver.disconnect();
// stop animation loop
this.stop();
// remove players from space
this.removeAll();
return this;
}
/**
* Get a [`MediaRecorder`](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder) to record the current CanvasSpace. You can then call its `start()` function to start recording, and `stop()` to either download the video file or handle the blob data in the callback function you provided.
* @param downloadOrCallback Either `true` to download the video, or provide a callback function to handle the Blob data, when recording is completed.
* @param filetype video format. Default is "webm".
* @param bitrate bitrate per second
* @example `let rec = space.recorder(true); rec.start(); setTimeout( () => rec.stop(), 5000); // record 5s of video and download the file`
*/
recorder( downloadOrCallback: boolean | ( ( blobURL:string ) => {} ), filetype:string = "webm", bitrate:number = 15000000 ): MediaRecorder {
const stream = this._canvas.captureStream();
const recorder = new MediaRecorder( stream, { mimeType: `video/${filetype}`, bitsPerSecond: bitrate } );
recorder.ondataavailable = function( d ) {
const url = URL.createObjectURL( new Blob( [d.data], { type: `video/${filetype}` } ) );
if ( typeof downloadOrCallback === "function" ) {
downloadOrCallback( url );
} else if ( downloadOrCallback ) {
const a = document.createElement( "a" );
a.href = url;
a.download = `canvas_video.${filetype}`;
a.click();
a.remove();
}
};
return recorder;
}
}
/**
* CanvasForm is an implementation of abstract class [`VisualForm`](#link). It provide methods to express Pts on [`CanvasSpace`](#link).
* You may extend CanvasForm to implement your own expressions for CanvasSpace.
*/
export class CanvasForm extends VisualForm {
protected _space:CanvasSpace;
protected _ctx:RenderingContext2D;
protected _estimateTextWidth:( string ) => number;
/**
* store common styles so that they can be restored to canvas context when using multiple forms. See `reset()`.
*/
protected _style:DefaultFormStyle = {
fillStyle: "#f03", strokeStyle:"#fff",
lineWidth: 1, lineJoin: "bevel", lineCap: "butt",
globalAlpha: 1
};
/**
* Create a new CanvasForm. You may also use [`CanvasSpace.getForm()`](#link) to get the default form.
* @param space an instance of CanvasSpace
*/
constructor( space?:CanvasSpace | RenderingContext2D ) {
super();
// allow for undefined context to support custom contexts via subclassing.
if ( !space ) return this;
const _setup = ( ctx ) => {
this._ctx = ctx;
this._ctx.fillStyle = this._style.fillStyle;
this._ctx.strokeStyle = this._style.strokeStyle;
this._ctx.lineJoin = "bevel";
this._ctx.font = this._font.value;
this._ready = true;
};
if ( space instanceof CanvasSpace ) {
this._space = space;
if ( this._space.ready && this._space.ctx ) {
_setup( this._space.ctx );
} else {
this._space.add( { start: () => {
_setup( this._space.ctx );
}} );
}
} else {
_setup( space );
}
}
/**
* get the CanvasSpace instance that this form is associated with
*/
get space():CanvasSpace { return this._space; }
/**
* Get the rendering context of canvas to perform other canvas functions.
* @example `form.ctx.clip()`
*/
get ctx():RenderingContext2D { return this._ctx; }
/**
* Toggle whether to draw on offscreen canvas (if offscreen is set in CanvasSpace)
* @param off if `true`, draw on offscreen canvas instead of the visible canvas. Default is `true`
* @param clear optionally provide a valid color string to fill a bg color. see CanvasSpace's `clearOffscreen` function.
*/
useOffscreen( off:boolean = true, clear:boolean | string = false ) {
if ( clear ) this._space.clearOffscreen( ( typeof clear == "string" ) ? clear : null );
this._ctx = ( this._space.hasOffscreen && off ) ? this._space.offscreenCtx : this._space.ctx;
return this;
}
/**
* Render the offscreen canvas's content on the visible canvas
* @param offset Optional offset on the top-left position when drawing on the visible canvas
*/
renderOffscreen( offset:PtLike = [0,0] ) {
if ( this._space.hasOffscreen ) {
this._space.ctx.drawImage(
this._space.offscreenCanvas, offset[0], offset[1], this._space.width, this._space.height );
}
}
/**
* Set current alpha value.
* @example `form.alpha(0.6)`
* @param a alpha value between 0 and 1
*/
alpha( a:number ):this {
this._ctx.globalAlpha = a;
this._style.globalAlpha = a;
return this;
}
/**
* Set current fill style. Provide a valid color string such as `"#FFF"` or `"rgba(255,0,100,0.5)"` or `false` to specify no fill color.
* @example `form.fill("#F90")`, `form.fill("rgba(0,0,0,.5")`, `form.fill(false)`
* @param c fill color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle))
*/
fill( c:string | boolean | CanvasGradient | CanvasPattern ):this {
if ( typeof c == "boolean" ) {
this.filled = c;
} else {
this.filled = true;
this._style.fillStyle = c;
this._ctx.fillStyle = c;
}
return this;
}
/**
* Set current fill style and remove stroke style.
* @param c fill color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle))
*/
fillOnly( c:string | boolean | CanvasGradient | CanvasPattern ):this {
this.stroke( false );
return this.fill( c );
}
/**
* Set current stroke style. Provide a valid color string or `false` to specify no stroke color.
* @example `form.stroke("#F90")`, `form.stroke("rgba(0,0,0,.5")`, `form.stroke(false)`, `form.stroke("#000", 0.5, 'round', 'square')`
* @param c stroke color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeStyle))
* @param width Optional value (can be floating point) to set line width
* @param linejoin Optional string to set line joint style. Can be "miter", "bevel", or "round".
* @param linecap Optional string to set line cap style. Can be "butt", "round", or "square".
*/
stroke( c:string | boolean | CanvasGradient | CanvasPattern, width?:number, linejoin?:CanvasLineJoin, linecap?:CanvasLineCap ):this {
if ( typeof c == "boolean" ) {
this.stroked = c;
} else {
this.stroked = true;
this._style.strokeStyle = c;
this._ctx.strokeStyle = c;
if ( width ) {
this._ctx.lineWidth = width;
this._style.lineWidth = width;
}
if ( linejoin ) {
this._ctx.lineJoin = linejoin;
this._style.lineJoin = linejoin;
}
if ( linecap ) {
this._ctx.lineCap = linecap;
this._style.lineCap = linecap;
}
}
return this;
}
/**
* Set stroke style and remove fill style.
* @param c stroke color which can be as color, gradient, or pattern. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeStyle))
* @param width Optional value (can be floating point) to set line width
* @param linejoin Optional string to set line joint style. Can be "miter", "bevel", or "round".
* @param linecap Optional string to set line cap style. Can be "butt", "round", or "square".
*/
strokeOnly( c:string | boolean | CanvasGradient | CanvasPattern, width?:number, linejoin?:CanvasLineJoin, linecap?:CanvasLineCap ):this {
this.fill( false );
return this.stroke( c, width, linejoin, linecap );
}
/**
* A convenient function to apply fill and/or stroke after custom drawings using canvas context (eg, `form.ctx.ellipse(...)`).
* You don't need to call this function if you're using Pts' drawing functions like `form.point` or `form.rect`
* @param filled apply fill when set to `true`
* @param stroked apply stroke when set to `true`
* @param strokeWidth optionally set a stroke width
* @example `form.ctx.beginPath(); form.ctx.ellipse(...); form.applyFillStroke();`
*/
applyFillStroke( filled:boolean | string = true, stroked:boolean | string = true, strokeWidth:number = 1 ) {
if ( filled ) {
if ( typeof filled === 'string' ) this.fill( filled );
this._ctx.fill();
}
if ( stroked ) {
if ( typeof stroked === 'string' ) this.stroke( stroked, strokeWidth );
this._ctx.stroke();
}
return this;
}
/**
* This function takes an array of gradient colors, and returns a function to define the areas of the gradient fill. See demo code in [CanvasForm.gradient](https://ptsjs.org/demo/?name=canvasform.textBox).
* @param stops an array of gradient stops. This can be an array of colors `["#f00", "#0f0", ...]` for evenly distributed gradient, or an array of [stop, color] like `[[0.1, "#f00"], [0.7, "#0f0"]]`
* @returns a function that takes 1 or 2 `Group` as parameters. Use a single `Group` to specify a rectangular area for linear gradient, or use 2 `Groups` to specify 2 `Circles` for radial gradient.
* @example `c1 = Circle.fromCenter(...); grad = form.gradient(["#f00", "#00f"]); form.fill( grad( c1, c2 ) ).circle( c1 )`
*/
gradient( stops:[number, string][] | string[] ):( ( area1:GroupLike, area2?:GroupLike ) => CanvasGradient ) {
const vals:[number, string][] = [];
if ( stops.length < 2 ) ( stops as [number, string][] ).push( [0.99, "#000"], [1,"#000"] );
for ( let i = 0, len = stops.length; i < len; i++ ) {
const t:number = typeof stops[i] === 'string' ? i * ( 1 / ( stops.length - 1 ) ) : stops[i][0] as number;
const v: string = typeof stops[i] === 'string' ? stops[i] as string : stops[i][1] as string;
vals.push( [t, v] );
}
return ( area1:GroupLike, area2?:GroupLike ) => {
const grad = area2
? this._ctx.createRadialGradient( area1[0][0], area1[0][1], Math.abs( area1[1][0] ), area2[0][0], area2[0][1], Math.abs( area2[1][0] ) )
: this._ctx.createLinearGradient( area1[0][0], area1[0][1], area1[1][0], area1[1][1] );
for ( let i = 0, len = vals.length; i < len; i++ ) {
grad.addColorStop( vals[i][0], vals[i][1] );
}
return grad;
};
}
/**
* Set composite operation (also known as blend mode). You can also call this function without parameters to get back to default 'source-over' mode. See [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation) for the full list of operations you can use.
* @param mode a composite operation such as 'lighten', 'multiply', 'overlay', and 'color-burn'.
*/
composite( mode:GlobalCompositeOperation = 'source-over' ):this {
this._ctx.globalCompositeOperation = mode;
return this;
}
/**
* Create a clipping mask from the current path. See [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clip) for details.
*/
clip():this {
this._ctx.clip();
return this;
}
/**
* Activate dashed stroke and set dash style. You can customize the segments and offset.
* @example `form.dash()`, `form.dash([5, 10])`, `form.dash([5, 5], 5)`, `form.dash(false)`
* @param segments Dash segments. Defaults to `true` which corresponds to `[5, 5]`. Pass `false` to deactivate dashes. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash))
* @param offset Dash offset. Defaults to 0. (See [canvas documentation](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset)
*/
dash( segments:PtLike | boolean = true, offset:number = 0 ):this {
if ( !segments ) {
// false or [], deactivate dashed strokes
this._ctx.setLineDash( [] );
this._ctx.lineDashOffset = 0;
} else {
if ( segments === true ) {
segments = [5, 5];
}
this._ctx.setLineDash( [segments[0], segments[1]] );
this._ctx.lineDashOffset = offset;
}
return this;
}
/**
* Set the current font.
* @param sizeOrFont either a number to specify font-size, or a `Font` object to specify all font properties
* @param weight Optional font-weight string such as "bold"
* @param style Optional font-style string such as "italic"
* @param lineHeight Optional line-height number suchas 1.5
* @param family Optional font-family such as "Helvetica, sans-serif"
* @example `form.font( myFont )`, `form.font(14, "bold")`
*/
font( sizeOrFont:number | Font, weight?:string, style?:string, lineHeight?:number, family?:string ):this {
if ( typeof sizeOrFont == "number" ) {
this._font.size = sizeOrFont;
if ( family ) this._font.face = family;
if ( weight ) this._font.weight = weight;
if ( style ) this._font.style = style;
if ( lineHeight ) this._font.lineHeight = lineHeight;
} else {
this._font = sizeOrFont;
}
this._ctx.font = this._font.value;
// If using estimate, reapply it when font changes.
if ( this._estimateTextWidth ) this.fontWidthEstimate( true );
return this;
}
/**
* Set whether to use html canvas' [`measureText`](#link) function, or a faster but less accurate heuristic function.
* @param estimate `true` to use heuristic function, or `false` to use ctx.measureText
*/
fontWidthEstimate( estimate:boolean = true ):this {
this._estimateTextWidth = ( estimate ) ? Typo.textWidthEstimator( ( ( c:string ) => this._ctx.measureText( c ).width ) ) : undefined;
return this;
}
/**
* Get the width of this text. It will return an actual measurement or an estimate based on [`fontWidthEstimate`](#link) setting. Default is an actual measurement using canvas context's measureText.
* @param c a string of text contents
*/
getTextWidth( c:string ):number {
return ( !this._estimateTextWidth ) ? this._ctx.measureText( c + " ." ).width : this._estimateTextWidth( c );
}
/**
* Truncate text to fit width.
* @param str text to truncate
* @param width width to fit
* @param tail text to indicate overflow such as "...". Default is empty "".
*/
protected _textTruncate( str:string, width:number, tail:string = "" ):[string, number] {
return Typo.truncate( this.getTextWidth.bind( this ), str, width, tail );
}
/**
* Align text within a rectangle box.
* @param box a Group or an Iterable<PtLike> that defines a rectangular box
* @param vertical a string that specifies the vertical alignment in the box: "top", "bottom", "middle", "start", "end"
* @param offset Optional offset from the edge (like padding)
* @param center Optional center position
*/
protected _textAlign( box:PtLikeIterable, vertical:string, offset?:PtLike, center?:Pt ):Pt {
const _box = Util.iterToArray( box );
if ( !Util.arrayCheck( _box ) ) return;
if ( !center ) center = Rectangle.center( _box );
let px = _box[0][0];
if ( this._ctx.textAlign == "end" || this._ctx.textAlign == "right" ) {
px = _box[1][0];
// @ts-ignore
} else if ( this._ctx.textAlign == "center" || this._ctx.textAlign == "middle" ) {
px = center[0];
}
let py = center[1];
if ( vertical == "top" || vertical == "start" ) {
py = _box[0][1];
} else if ( vertical == "end" || vertical == "bottom" ) {
py = _box[1][1];
}
return ( offset ) ? new Pt( px + offset[0], py + offset[1] ) : new Pt( px, py );
}
/**
* Reset the rendering context's common styles to this form's styles. This supports using multiple forms on the same canvas context.
*/
reset():this {
for ( const k in this._style ) {
if ( this._style.hasOwnProperty( k ) ) {
this._ctx[k] = this._style[k];
}
}
this._font = new Font();
this._ctx.font = this._font.value;
return this;
}
protected _paint() {
if ( this._filled ) this._ctx.fill();
if ( this._stroked ) this._ctx.stroke();
}
/**
* A static function to draw a point.
* @param ctx canvas rendering context
* @param p a Pt object
* @param radius radius of the point. Default is 5.
* @param shape The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.
* @example `form.point( p )`, `form.point( p, 10, "circle" )`
*/
static point( ctx:RenderingContext2D, p:PtLike, radius:number = 5, shape:string = "square" ) {
if ( !p ) return;
if ( !CanvasForm[shape] ) throw new Error( `${shape} is not a static function of CanvasForm` );
CanvasForm[shape]( ctx, p, radius );
}
/**
* Draws a point.
* @param p a Pt object
* @param radius radius of the point. Default is 5.
* @param shape The shape of the point. Defaults to "square", but it can be "circle" or a custom shape function in your own implementation.
* @example `form.point( p )`, `form.point( p, 10, "circle" )`
*/
point( p:PtLike, radius:number = 5, shape:string = "square" ):this {
CanvasForm.point( this._ctx, p, radius, shape );
this._paint();
return this;
}
/**
* A static function to draw a circle.
* @param ctx canvas rendering context
* @param pt center position of the circle
* @param radius radius of the circle
*/
static circle( ctx:RenderingContext2D, pt:PtLike, radius:number = 10 ) {
if ( !pt ) return;
ctx.beginPath();
ctx.arc( pt[0], pt[1], radius, 0, Const.two_pi, false );
ctx.closePath();
}
/**
* Draw a circle. See also [`Circle.fromCenter`](#link)
* @param pts usually a Group or an Iterable<PtLike> with 2 Pt, but it can also take an array of two numeric arrays [ [position], [size] ]
*/
circle( pts:PtLikeIterable ):this {
const p = Util.iterToArray( pts );
CanvasForm.circle( this._ctx, p[0], p[1][0] );
this._paint();
return this;
}
/**
* A static function to draw an ellipse.
* @param ctx canvas rendering context
* @param pt center position
* @param radius radius [x, y] of the ellipse
* @param rotation rotation of the ellipse in radian. Default is 0.
* @param startAngle start angle of the ellipse. Default is 0.
* @param endAngle end angle of the ellipse. Default is 2 PI.
* @param cc an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.
*/
static ellipse( ctx:RenderingContext2D, pt:PtLike, radius:PtLike, rotation:number = 0, startAngle:number = 0, endAngle:number = Const.two_pi, cc:boolean = false ) {
if ( !pt || !radius ) return;
ctx.beginPath();
ctx.ellipse( pt[0], pt[1], radius[0], radius[1], rotation, startAngle, endAngle, cc );
}
/**
* Draw an ellipse.
* @param pt center position
* @param radius radius [x, y] of the ellipse
* @param rotation rotation of the ellipse in radian. Default is 0.
* @param startAngle start angle of the ellipse. Default is 0.
* @param endAngle end angle of the ellipse. Default is 2 PI.
* @param cc an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.
*/
ellipse( pt:PtLike, radius:PtLike, rotation:number = 0, startAngle:number = 0, endAngle:number = Const.two_pi, cc:boolean = false ) {
CanvasForm.ellipse( this._ctx, pt, radius, rotation, startAngle, endAngle, cc );
this._paint();
return this;
}
/**
* A static function to draw an arc.
* @param ctx canvas rendering context
* @param pt center position
* @param radius radius of the arc circle
* @param startAngle start angle of the arc
* @param endAngle end angle of the arc
* @param cc an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.
*/
static arc( ctx:RenderingContext2D, pt:PtLike, radius:number, startAngle:number, endAngle:number, cc?:boolean ) {
if ( !pt ) return;
ctx.beginPath();
ctx.arc( pt[0], pt[1], radius, startAngle, endAngle, cc );
}
/**
* Draw an arc.
* @param pt center position
* @param radius radius of the arc circle
* @param startAngle start angle of the arc
* @param endAngle end angle of the arc
* @param cc an optional boolean value to specify if it should be drawn clockwise (`false`) or counter-clockwise (`true`). Default is clockwise.
*/
arc( pt:PtLike, radius:number, startAngle:number, endAngle:number, cc?:boolean ):this {
CanvasForm.arc( this._ctx, pt, radius, startAngle, endAngle, cc );
this._paint();
return this;
}
/**
* A static function to draw a square.
* @param ctx canvas rendering context
* @param pt center position of the square
* @param halfsize half size of the square
*/
static square( ctx:RenderingContext2D, pt:PtLike, halfsize:number ) {
if ( !pt ) return;
const x1 = pt[0] - halfsize;
const y1 = pt[1] - halfsize;
const x2 = pt[0] + halfsize;
const y2 = pt[1] + halfsize;
// faster than using `rect`
ctx.beginPath();
ctx.moveTo( x1, y1 );
ctx.lineTo( x1, y2 );
ctx.lineTo( x2, y2 );
ctx.lineTo( x2, y1 );
ctx.closePath();
}
/**
* Draw a square, given a center and its half-size.
* @param pt center Pt
* @param halfsize half-size
*/
square( pt:PtLike, halfsize:number ) {
CanvasForm.square( this._ctx, pt, halfsize );
this._paint();
return this;
}
/**
* A static function to draw a line or polyline.
* @param ctx canvas rendering context
* @param pts a Group or an Iterable<PtLike> representing a line
*/
static line( ctx:RenderingContext2D, pts:PtLikeIterable ) {
if ( !Util.arrayCheck( pts ) ) return;
let i = 0;
ctx.beginPath();
for ( const it of pts ) {
if ( it ) {