-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathcontext2d.js
2682 lines (2456 loc) · 78.3 KB
/
context2d.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
/* eslint-disable no-fallthrough */
/* eslint-disable no-console */
/**
* @license
* jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) [email protected]
*
* Licensed under the MIT License. http://opensource.org/licenses/mit-license
*/
import { jsPDF } from "../jspdf.js";
import { RGBColor } from "../libs/rgbcolor.js";
import { console } from "../libs/console.js";
import {
buildFontFaceMap,
parseFontFamily,
resolveFontFace
} from "../libs/fontFace.js";
/**
* This plugin mimics the HTML5 CanvasRenderingContext2D.
*
* The goal is to provide a way for current canvas implementations to print directly to a PDF.
*
* @name context2d
* @module
*/
(function(jsPDFAPI) {
"use strict";
var ContextLayer = function(ctx) {
ctx = ctx || {};
this.isStrokeTransparent = ctx.isStrokeTransparent || false;
this.strokeOpacity = ctx.strokeOpacity || 1;
this.strokeStyle = ctx.strokeStyle || "#000000";
this.fillStyle = ctx.fillStyle || "#000000";
this.isFillTransparent = ctx.isFillTransparent || false;
this.fillOpacity = ctx.fillOpacity || 1;
this.font = ctx.font || "10px sans-serif";
this.textBaseline = ctx.textBaseline || "alphabetic";
this.textAlign = ctx.textAlign || "left";
this.lineWidth = ctx.lineWidth || 1;
this.lineJoin = ctx.lineJoin || "miter";
this.lineCap = ctx.lineCap || "butt";
this.path = ctx.path || [];
this.transform =
typeof ctx.transform !== "undefined"
? ctx.transform.clone()
: new Matrix();
this.globalCompositeOperation = ctx.globalCompositeOperation || "normal";
this.globalAlpha = ctx.globalAlpha || 1.0;
this.clip_path = ctx.clip_path || [];
this.currentPoint = ctx.currentPoint || new Point();
this.miterLimit = ctx.miterLimit || 10.0;
this.lastPoint = ctx.lastPoint || new Point();
this.lineDashOffset = ctx.lineDashOffset || 0.0;
this.lineDash = ctx.lineDash || [];
this.margin = ctx.margin || [0, 0, 0, 0];
this.prevPageLastElemOffset = ctx.prevPageLastElemOffset || 0;
this.ignoreClearRect =
typeof ctx.ignoreClearRect === "boolean" ? ctx.ignoreClearRect : true;
return this;
};
//stub
var f2,
getHorizontalCoordinateString,
getVerticalCoordinateString,
getHorizontalCoordinate,
getVerticalCoordinate,
Point,
Rectangle,
Matrix,
_ctx;
jsPDFAPI.events.push([
"initialized",
function() {
this.context2d = new Context2D(this);
f2 = this.internal.f2;
getHorizontalCoordinateString = this.internal.getCoordinateString;
getVerticalCoordinateString = this.internal.getVerticalCoordinateString;
getHorizontalCoordinate = this.internal.getHorizontalCoordinate;
getVerticalCoordinate = this.internal.getVerticalCoordinate;
Point = this.internal.Point;
Rectangle = this.internal.Rectangle;
Matrix = this.internal.Matrix;
_ctx = new ContextLayer();
}
]);
var Context2D = function(pdf) {
Object.defineProperty(this, "canvas", {
get: function() {
return { parentNode: false, style: false };
}
});
var _pdf = pdf;
Object.defineProperty(this, "pdf", {
get: function() {
return _pdf;
}
});
var _pageWrapXEnabled = false;
/**
* @name pageWrapXEnabled
* @type {boolean}
* @default false
*/
Object.defineProperty(this, "pageWrapXEnabled", {
get: function() {
return _pageWrapXEnabled;
},
set: function(value) {
_pageWrapXEnabled = Boolean(value);
}
});
var _pageWrapYEnabled = false;
/**
* @name pageWrapYEnabled
* @type {boolean}
* @default true
*/
Object.defineProperty(this, "pageWrapYEnabled", {
get: function() {
return _pageWrapYEnabled;
},
set: function(value) {
_pageWrapYEnabled = Boolean(value);
}
});
var _posX = 0;
/**
* @name posX
* @type {number}
* @default 0
*/
Object.defineProperty(this, "posX", {
get: function() {
return _posX;
},
set: function(value) {
if (!isNaN(value)) {
_posX = value;
}
}
});
var _posY = 0;
/**
* @name posY
* @type {number}
* @default 0
*/
Object.defineProperty(this, "posY", {
get: function() {
return _posY;
},
set: function(value) {
if (!isNaN(value)) {
_posY = value;
}
}
});
/**
* Gets or sets the page margin when using auto paging. Has no effect when {@link autoPaging} is off.
* @name margin
* @type {number|number[]}
* @default [0, 0, 0, 0]
*/
Object.defineProperty(this, "margin", {
get: function() {
return _ctx.margin;
},
set: function(value) {
var margin;
if (typeof value === "number") {
margin = [value, value, value, value];
} else {
margin = new Array(4);
margin[0] = value[0];
margin[1] = value.length >= 2 ? value[1] : margin[0];
margin[2] = value.length >= 3 ? value[2] : margin[0];
margin[3] = value.length >= 4 ? value[3] : margin[1];
}
_ctx.margin = margin;
}
});
var _autoPaging = false;
/**
* Gets or sets the auto paging mode. When auto paging is enabled, the context2d will automatically draw on the
* next page if a shape or text chunk doesn't fit entirely on the current page. The context2d will create new
* pages if required.
*
* Context2d supports different modes:
* <ul>
* <li>
* <code>false</code>: Auto paging is disabled.
* </li>
* <li>
* <code>true</code> or <code>'slice'</code>: Will cut shapes or text chunks across page breaks. Will possibly
* slice text in half, making it difficult to read.
* </li>
* <li>
* <code>'text'</code>: Trys not to cut text in half across page breaks. Works best for documents consisting
* mostly of a single column of text.
* </li>
* </ul>
* @name Context2D#autoPaging
* @type {boolean|"slice"|"text"}
* @default false
*/
Object.defineProperty(this, "autoPaging", {
get: function() {
return _autoPaging;
},
set: function(value) {
_autoPaging = value;
}
});
var lastBreak = 0;
/**
* @name lastBreak
* @type {number}
* @default 0
*/
Object.defineProperty(this, "lastBreak", {
get: function() {
return lastBreak;
},
set: function(value) {
lastBreak = value;
}
});
var pageBreaks = [];
/**
* Y Position of page breaks.
* @name pageBreaks
* @type {number}
* @default 0
*/
Object.defineProperty(this, "pageBreaks", {
get: function() {
return pageBreaks;
},
set: function(value) {
pageBreaks = value;
}
});
/**
* @name ctx
* @type {object}
* @default {}
*/
Object.defineProperty(this, "ctx", {
get: function() {
return _ctx;
},
set: function(value) {
if (value instanceof ContextLayer) {
_ctx = value;
}
}
});
/**
* @name path
* @type {array}
* @default []
*/
Object.defineProperty(this, "path", {
get: function() {
return _ctx.path;
},
set: function(value) {
_ctx.path = value;
}
});
/**
* @name ctxStack
* @type {array}
* @default []
*/
var _ctxStack = [];
Object.defineProperty(this, "ctxStack", {
get: function() {
return _ctxStack;
},
set: function(value) {
_ctxStack = value;
}
});
/**
* Sets or returns the color, gradient, or pattern used to fill the drawing
*
* @name fillStyle
* @default #000000
* @property {(color|gradient|pattern)} value The color of the drawing. Default value is #000000<br />
* A gradient object (linear or radial) used to fill the drawing (not supported by context2d)<br />
* A pattern object to use to fill the drawing (not supported by context2d)
*/
Object.defineProperty(this, "fillStyle", {
get: function() {
return this.ctx.fillStyle;
},
set: function(value) {
var rgba;
rgba = getRGBA(value);
this.ctx.fillStyle = rgba.style;
this.ctx.isFillTransparent = rgba.a === 0;
this.ctx.fillOpacity = rgba.a;
this.pdf.setFillColor(rgba.r, rgba.g, rgba.b, { a: rgba.a });
this.pdf.setTextColor(rgba.r, rgba.g, rgba.b, { a: rgba.a });
}
});
/**
* Sets or returns the color, gradient, or pattern used for strokes
*
* @name strokeStyle
* @default #000000
* @property {color} color A CSS color value that indicates the stroke color of the drawing. Default value is #000000 (not supported by context2d)
* @property {gradient} gradient A gradient object (linear or radial) used to create a gradient stroke (not supported by context2d)
* @property {pattern} pattern A pattern object used to create a pattern stroke (not supported by context2d)
*/
Object.defineProperty(this, "strokeStyle", {
get: function() {
return this.ctx.strokeStyle;
},
set: function(value) {
var rgba = getRGBA(value);
this.ctx.strokeStyle = rgba.style;
this.ctx.isStrokeTransparent = rgba.a === 0;
this.ctx.strokeOpacity = rgba.a;
if (rgba.a === 0) {
this.pdf.setDrawColor(255, 255, 255);
} else if (rgba.a === 1) {
this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
} else {
this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
}
}
});
/**
* Sets or returns the style of the end caps for a line
*
* @name lineCap
* @default butt
* @property {(butt|round|square)} lineCap butt A flat edge is added to each end of the line <br/>
* round A rounded end cap is added to each end of the line<br/>
* square A square end cap is added to each end of the line<br/>
*/
Object.defineProperty(this, "lineCap", {
get: function() {
return this.ctx.lineCap;
},
set: function(value) {
if (["butt", "round", "square"].indexOf(value) !== -1) {
this.ctx.lineCap = value;
this.pdf.setLineCap(value);
}
}
});
/**
* Sets or returns the current line width
*
* @name lineWidth
* @default 1
* @property {number} lineWidth The current line width, in pixels
*/
Object.defineProperty(this, "lineWidth", {
get: function() {
return this.ctx.lineWidth;
},
set: function(value) {
if (!isNaN(value)) {
this.ctx.lineWidth = value;
this.pdf.setLineWidth(value);
}
}
});
/**
* Sets or returns the type of corner created, when two lines meet
*/
Object.defineProperty(this, "lineJoin", {
get: function() {
return this.ctx.lineJoin;
},
set: function(value) {
if (["bevel", "round", "miter"].indexOf(value) !== -1) {
this.ctx.lineJoin = value;
this.pdf.setLineJoin(value);
}
}
});
/**
* A number specifying the miter limit ratio in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. The default value is 10.0.
*
* @name miterLimit
* @default 10
*/
Object.defineProperty(this, "miterLimit", {
get: function() {
return this.ctx.miterLimit;
},
set: function(value) {
if (!isNaN(value)) {
this.ctx.miterLimit = value;
this.pdf.setMiterLimit(value);
}
}
});
Object.defineProperty(this, "textBaseline", {
get: function() {
return this.ctx.textBaseline;
},
set: function(value) {
this.ctx.textBaseline = value;
}
});
Object.defineProperty(this, "textAlign", {
get: function() {
return this.ctx.textAlign;
},
set: function(value) {
if (["right", "end", "center", "left", "start"].indexOf(value) !== -1) {
this.ctx.textAlign = value;
}
}
});
var _fontFaceMap = null;
function getFontFaceMap(pdf, fontFaces) {
if (_fontFaceMap === null) {
var fontMap = pdf.getFontList();
var convertedFontFaces = convertToFontFaces(fontMap);
_fontFaceMap = buildFontFaceMap(convertedFontFaces.concat(fontFaces));
}
return _fontFaceMap;
}
function convertToFontFaces(fontMap) {
var fontFaces = [];
Object.keys(fontMap).forEach(function(family) {
var styles = fontMap[family];
styles.forEach(function(style) {
var fontFace = null;
switch (style) {
case "bold":
fontFace = {
family: family,
weight: "bold"
};
break;
case "italic":
fontFace = {
family: family,
style: "italic"
};
break;
case "bolditalic":
fontFace = {
family: family,
weight: "bold",
style: "italic"
};
break;
case "":
case "normal":
fontFace = {
family: family
};
break;
}
// If font-face is still null here, it is a font with some styling we don't recognize and
// cannot map or it is a font added via the fontFaces option of .html().
if (fontFace !== null) {
fontFace.ref = {
name: family,
style: style
};
fontFaces.push(fontFace);
}
});
});
return fontFaces;
}
var _fontFaces = null;
/**
* A map of available font-faces, as passed in the options of
* .html(). If set a limited implementation of the font style matching
* algorithm defined by https://www.w3.org/TR/css-fonts-3/#font-matching-algorithm
* will be used. If not set it will fallback to previous behavior.
*/
Object.defineProperty(this, "fontFaces", {
get: function() {
return _fontFaces;
},
set: function(value) {
_fontFaceMap = null;
_fontFaces = value;
}
});
Object.defineProperty(this, "font", {
get: function() {
return this.ctx.font;
},
set: function(value) {
this.ctx.font = value;
var rx, matches;
//source: https://stackoverflow.com/a/10136041
// eslint-disable-next-line no-useless-escape
rx = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z]+?)\s*$/i;
matches = rx.exec(value);
if (matches !== null) {
var fontStyle = matches[1];
var fontVariant = matches[2];
var fontWeight = matches[3];
var fontSize = matches[4];
var lineHeight = matches[5];
var fontFamily = matches[6];
} else {
return;
}
var rxFontSize = /^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i;
var fontSizeUnit = rxFontSize.exec(fontSize)[2];
if ("px" === fontSizeUnit) {
fontSize = Math.floor(
parseFloat(fontSize) * this.pdf.internal.scaleFactor
);
} else if ("em" === fontSizeUnit) {
fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
} else {
fontSize = Math.floor(
parseFloat(fontSize) * this.pdf.internal.scaleFactor
);
}
this.pdf.setFontSize(fontSize);
var parts = parseFontFamily(fontFamily);
if (this.fontFaces) {
var fontFaceMap = getFontFaceMap(this.pdf, this.fontFaces);
var rules = parts.map(function(ff) {
return {
family: ff,
stretch: "normal", // TODO: Extract font-stretch from font rule (perhaps write proper parser for it?)
weight: fontWeight,
style: fontStyle
};
});
var font = resolveFontFace(fontFaceMap, rules);
this.pdf.setFont(font.ref.name, font.ref.style);
return;
}
var style = "";
if (
fontWeight === "bold" ||
parseInt(fontWeight, 10) >= 700 ||
fontStyle === "bold"
) {
style = "bold";
}
if (fontStyle === "italic") {
style += "italic";
}
if (style.length === 0) {
style = "normal";
}
var jsPdfFontName = "";
var fallbackFonts = {
arial: "Helvetica",
Arial: "Helvetica",
verdana: "Helvetica",
Verdana: "Helvetica",
helvetica: "Helvetica",
Helvetica: "Helvetica",
"sans-serif": "Helvetica",
fixed: "Courier",
monospace: "Courier",
terminal: "Courier",
cursive: "Times",
fantasy: "Times",
serif: "Times"
};
for (var i = 0; i < parts.length; i++) {
if (
this.pdf.internal.getFont(parts[i], style, {
noFallback: true,
disableWarning: true
}) !== undefined
) {
jsPdfFontName = parts[i];
break;
} else if (
style === "bolditalic" &&
this.pdf.internal.getFont(parts[i], "bold", {
noFallback: true,
disableWarning: true
}) !== undefined
) {
jsPdfFontName = parts[i];
style = "bold";
} else if (
this.pdf.internal.getFont(parts[i], "normal", {
noFallback: true,
disableWarning: true
}) !== undefined
) {
jsPdfFontName = parts[i];
style = "normal";
break;
}
}
if (jsPdfFontName === "") {
for (var j = 0; j < parts.length; j++) {
if (fallbackFonts[parts[j]]) {
jsPdfFontName = fallbackFonts[parts[j]];
break;
}
}
}
jsPdfFontName = jsPdfFontName === "" ? "Times" : jsPdfFontName;
this.pdf.setFont(jsPdfFontName, style);
}
});
Object.defineProperty(this, "globalCompositeOperation", {
get: function() {
return this.ctx.globalCompositeOperation;
},
set: function(value) {
this.ctx.globalCompositeOperation = value;
}
});
Object.defineProperty(this, "globalAlpha", {
get: function() {
return this.ctx.globalAlpha;
},
set: function(value) {
this.ctx.globalAlpha = value;
}
});
/**
* A float specifying the amount of the line dash offset. The default value is 0.0.
*
* @name lineDashOffset
* @default 0.0
*/
Object.defineProperty(this, "lineDashOffset", {
get: function() {
return this.ctx.lineDashOffset;
},
set: function(value) {
this.ctx.lineDashOffset = value;
setLineDash.call(this);
}
});
// Not HTML API
Object.defineProperty(this, "lineDash", {
get: function() {
return this.ctx.lineDash;
},
set: function(value) {
this.ctx.lineDash = value;
setLineDash.call(this);
}
});
// Not HTML API
Object.defineProperty(this, "ignoreClearRect", {
get: function() {
return this.ctx.ignoreClearRect;
},
set: function(value) {
this.ctx.ignoreClearRect = Boolean(value);
}
});
};
/**
* Sets the line dash pattern used when stroking lines.
* @name setLineDash
* @function
* @description It uses an array of values that specify alternating lengths of lines and gaps which describe the pattern.
*/
Context2D.prototype.setLineDash = function(dashArray) {
this.lineDash = dashArray;
};
/**
* gets the current line dash pattern.
* @name getLineDash
* @function
* @returns {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].
*/
Context2D.prototype.getLineDash = function() {
if (this.lineDash.length % 2) {
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getLineDash#return_value
return this.lineDash.concat(this.lineDash);
} else {
// The copied value is returned to prevent contamination from outside.
return this.lineDash.slice();
}
};
Context2D.prototype.fill = function() {
pathPreProcess.call(this, "fill", false);
};
/**
* Actually draws the path you have defined
*
* @name stroke
* @function
* @description The stroke() method actually draws the path you have defined with all those moveTo() and lineTo() methods. The default color is black.
*/
Context2D.prototype.stroke = function() {
pathPreProcess.call(this, "stroke", false);
};
/**
* Begins a path, or resets the current
*
* @name beginPath
* @function
* @description The beginPath() method begins a path, or resets the current path.
*/
Context2D.prototype.beginPath = function() {
this.path = [
{
type: "begin"
}
];
};
/**
* Moves the path to the specified point in the canvas, without creating a line
*
* @name moveTo
* @function
* @param x {Number} The x-coordinate of where to move the path to
* @param y {Number} The y-coordinate of where to move the path to
*/
Context2D.prototype.moveTo = function(x, y) {
if (isNaN(x) || isNaN(y)) {
console.error("jsPDF.context2d.moveTo: Invalid arguments", arguments);
throw new Error("Invalid arguments passed to jsPDF.context2d.moveTo");
}
var pt = this.ctx.transform.applyToPoint(new Point(x, y));
this.path.push({
type: "mt",
x: pt.x,
y: pt.y
});
this.ctx.lastPoint = new Point(x, y);
};
/**
* Creates a path from the current point back to the starting point
*
* @name closePath
* @function
* @description The closePath() method creates a path from the current point back to the starting point.
*/
Context2D.prototype.closePath = function() {
var pathBegin = new Point(0, 0);
var i = 0;
for (i = this.path.length - 1; i !== -1; i--) {
if (this.path[i].type === "begin") {
if (
typeof this.path[i + 1] === "object" &&
typeof this.path[i + 1].x === "number"
) {
pathBegin = new Point(this.path[i + 1].x, this.path[i + 1].y);
break;
}
}
}
this.path.push({
type: "close"
});
this.ctx.lastPoint = new Point(pathBegin.x, pathBegin.y);
};
/**
* Adds a new point and creates a line to that point from the last specified point in the canvas
*
* @name lineTo
* @function
* @param x The x-coordinate of where to create the line to
* @param y The y-coordinate of where to create the line to
* @description The lineTo() method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line).
*/
Context2D.prototype.lineTo = function(x, y) {
if (isNaN(x) || isNaN(y)) {
console.error("jsPDF.context2d.lineTo: Invalid arguments", arguments);
throw new Error("Invalid arguments passed to jsPDF.context2d.lineTo");
}
var pt = this.ctx.transform.applyToPoint(new Point(x, y));
this.path.push({
type: "lt",
x: pt.x,
y: pt.y
});
this.ctx.lastPoint = new Point(pt.x, pt.y);
};
/**
* Clips a region of any shape and size from the original canvas
*
* @name clip
* @function
* @description The clip() method clips a region of any shape and size from the original canvas.
*/
Context2D.prototype.clip = function() {
this.ctx.clip_path = JSON.parse(JSON.stringify(this.path));
pathPreProcess.call(this, null, true);
};
/**
* Creates a cubic Bézier curve
*
* @name quadraticCurveTo
* @function
* @param cpx {Number} The x-coordinate of the Bézier control point
* @param cpy {Number} The y-coordinate of the Bézier control point
* @param x {Number} The x-coordinate of the ending point
* @param y {Number} The y-coordinate of the ending point
* @description The quadraticCurveTo() method adds a point to the current path by using the specified control points that represent a quadratic Bézier curve.<br /><br /> A quadratic Bézier curve requires two points. The first point is a control point that is used in the quadratic Bézier calculation and the second point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.
*/
Context2D.prototype.quadraticCurveTo = function(cpx, cpy, x, y) {
if (isNaN(x) || isNaN(y) || isNaN(cpx) || isNaN(cpy)) {
console.error(
"jsPDF.context2d.quadraticCurveTo: Invalid arguments",
arguments
);
throw new Error(
"Invalid arguments passed to jsPDF.context2d.quadraticCurveTo"
);
}
var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));
var pt1 = this.ctx.transform.applyToPoint(new Point(cpx, cpy));
this.path.push({
type: "qct",
x1: pt1.x,
y1: pt1.y,
x: pt0.x,
y: pt0.y
});
this.ctx.lastPoint = new Point(pt0.x, pt0.y);
};
/**
* Creates a cubic Bézier curve
*
* @name bezierCurveTo
* @function
* @param cp1x {Number} The x-coordinate of the first Bézier control point
* @param cp1y {Number} The y-coordinate of the first Bézier control point
* @param cp2x {Number} The x-coordinate of the second Bézier control point
* @param cp2y {Number} The y-coordinate of the second Bézier control point
* @param x {Number} The x-coordinate of the ending point
* @param y {Number} The y-coordinate of the ending point
* @description The bezierCurveTo() method adds a point to the current path by using the specified control points that represent a cubic Bézier curve. <br /><br />A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.
*/
Context2D.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {
if (
isNaN(x) ||
isNaN(y) ||
isNaN(cp1x) ||
isNaN(cp1y) ||
isNaN(cp2x) ||
isNaN(cp2y)
) {
console.error(
"jsPDF.context2d.bezierCurveTo: Invalid arguments",
arguments
);
throw new Error(
"Invalid arguments passed to jsPDF.context2d.bezierCurveTo"
);
}
var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));
var pt1 = this.ctx.transform.applyToPoint(new Point(cp1x, cp1y));
var pt2 = this.ctx.transform.applyToPoint(new Point(cp2x, cp2y));
this.path.push({
type: "bct",
x1: pt1.x,
y1: pt1.y,
x2: pt2.x,
y2: pt2.y,
x: pt0.x,
y: pt0.y
});
this.ctx.lastPoint = new Point(pt0.x, pt0.y);
};
/**
* Creates an arc/curve (used to create circles, or parts of circles)
*
* @name arc
* @function
* @param x {Number} The x-coordinate of the center of the circle
* @param y {Number} The y-coordinate of the center of the circle
* @param radius {Number} The radius of the circle
* @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
* @param endAngle {Number} The ending angle, in radians
* @param counterclockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
* @description The arc() method creates an arc/curve (used to create circles, or parts of circles).
*/
Context2D.prototype.arc = function(
x,
y,
radius,
startAngle,
endAngle,
counterclockwise
) {
if (
isNaN(x) ||
isNaN(y) ||
isNaN(radius) ||
isNaN(startAngle) ||
isNaN(endAngle)
) {
console.error("jsPDF.context2d.arc: Invalid arguments", arguments);
throw new Error("Invalid arguments passed to jsPDF.context2d.arc");
}
counterclockwise = Boolean(counterclockwise);
if (!this.ctx.transform.isIdentity) {
var xpt = this.ctx.transform.applyToPoint(new Point(x, y));
x = xpt.x;
y = xpt.y;
var x_radPt = this.ctx.transform.applyToPoint(new Point(0, radius));
var x_radPt0 = this.ctx.transform.applyToPoint(new Point(0, 0));
radius = Math.sqrt(
Math.pow(x_radPt.x - x_radPt0.x, 2) +
Math.pow(x_radPt.y - x_radPt0.y, 2)
);
}
if (Math.abs(endAngle - startAngle) >= 2 * Math.PI) {
startAngle = 0;