konva 10.3.3 → 10.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +1 -1
  2. package/konva.js +1576 -1636
  3. package/konva.min.js +4 -4
  4. package/lib/Animation.d.ts +63 -3
  5. package/lib/Animation.js +86 -65
  6. package/lib/BezierFunctions.d.ts +10 -0
  7. package/lib/BezierFunctions.js +32 -0
  8. package/lib/Canvas.d.ts +53 -0
  9. package/lib/Canvas.js +93 -34
  10. package/lib/Container.d.ts +156 -9
  11. package/lib/Container.js +260 -25
  12. package/lib/Context.d.ts +247 -0
  13. package/lib/Context.js +312 -74
  14. package/lib/Core.js +1 -0
  15. package/lib/DragAndDrop.d.ts +2 -0
  16. package/lib/DragAndDrop.js +92 -21
  17. package/lib/Factory.d.ts +24 -1
  18. package/lib/Factory.js +14 -20
  19. package/lib/FastLayer.d.ts +14 -1
  20. package/lib/FastLayer.js +14 -1
  21. package/lib/Global.d.ts +114 -3
  22. package/lib/Global.js +134 -5
  23. package/lib/Group.d.ts +11 -0
  24. package/lib/Group.js +11 -0
  25. package/lib/Layer.d.ts +128 -3
  26. package/lib/Layer.js +260 -49
  27. package/lib/Node.d.ts +703 -32
  28. package/lib/Node.js +1545 -202
  29. package/lib/PointerEvents.d.ts +2 -1
  30. package/lib/PointerEvents.js +19 -1
  31. package/lib/Shape.d.ts +99 -14
  32. package/lib/Shape.js +1101 -67
  33. package/lib/Stage.d.ts +85 -2
  34. package/lib/Stage.js +205 -14
  35. package/lib/Tween.d.ts +159 -4
  36. package/lib/Tween.js +243 -24
  37. package/lib/Util.d.ts +148 -4
  38. package/lib/Util.js +354 -82
  39. package/lib/Validators.d.ts +0 -2
  40. package/lib/Validators.js +3 -25
  41. package/lib/_CoreInternals.d.ts +12 -6
  42. package/lib/_CoreInternals.js +1 -0
  43. package/lib/_FullInternals.d.ts +17 -6
  44. package/lib/_FullInternals.js +7 -0
  45. package/lib/canvas-backend.js +6 -0
  46. package/lib/filters/Blur.d.ts +18 -0
  47. package/lib/filters/Blur.js +97 -24
  48. package/lib/filters/Brighten.d.ts +21 -0
  49. package/lib/filters/Brighten.js +24 -0
  50. package/lib/filters/Brightness.d.ts +11 -0
  51. package/lib/filters/Brightness.js +16 -0
  52. package/lib/filters/Contrast.d.ts +10 -0
  53. package/lib/filters/Contrast.js +21 -0
  54. package/lib/filters/Emboss.d.ts +20 -0
  55. package/lib/filters/Emboss.js +68 -8
  56. package/lib/filters/Enhance.d.ts +14 -0
  57. package/lib/filters/Enhance.js +34 -0
  58. package/lib/filters/Grayscale.d.ts +9 -0
  59. package/lib/filters/Grayscale.js +12 -0
  60. package/lib/filters/HSL.d.ts +17 -0
  61. package/lib/filters/HSL.js +48 -5
  62. package/lib/filters/HSV.d.ts +18 -0
  63. package/lib/filters/HSV.js +49 -5
  64. package/lib/filters/Invert.d.ts +9 -0
  65. package/lib/filters/Invert.js +12 -0
  66. package/lib/filters/Kaleidoscope.d.ts +12 -0
  67. package/lib/filters/Kaleidoscope.js +83 -0
  68. package/lib/filters/Mask.d.ts +11 -0
  69. package/lib/filters/Mask.js +18 -0
  70. package/lib/filters/Noise.d.ts +19 -0
  71. package/lib/filters/Noise.js +19 -0
  72. package/lib/filters/Pixelate.d.ts +20 -0
  73. package/lib/filters/Pixelate.js +28 -1
  74. package/lib/filters/Posterize.d.ts +21 -0
  75. package/lib/filters/Posterize.js +22 -0
  76. package/lib/filters/RGB.d.ts +21 -0
  77. package/lib/filters/RGB.js +43 -28
  78. package/lib/filters/RGBA.d.ts +23 -0
  79. package/lib/filters/RGBA.js +28 -41
  80. package/lib/filters/Sepia.d.ts +9 -0
  81. package/lib/filters/Sepia.js +10 -0
  82. package/lib/filters/Solarize.d.ts +10 -0
  83. package/lib/filters/Solarize.js +11 -0
  84. package/lib/filters/Threshold.d.ts +22 -0
  85. package/lib/filters/Threshold.js +22 -0
  86. package/lib/shapes/Arc.d.ts +40 -0
  87. package/lib/shapes/Arc.js +89 -6
  88. package/lib/shapes/Arrow.d.ts +24 -1
  89. package/lib/shapes/Arrow.js +83 -0
  90. package/lib/shapes/Circle.d.ts +18 -0
  91. package/lib/shapes/Circle.js +36 -9
  92. package/lib/shapes/Ellipse.d.ts +34 -2
  93. package/lib/shapes/Ellipse.js +67 -9
  94. package/lib/shapes/Image.d.ts +49 -0
  95. package/lib/shapes/Image.js +151 -22
  96. package/lib/shapes/Label.d.ts +65 -1
  97. package/lib/shapes/Label.js +113 -20
  98. package/lib/shapes/Line.d.ts +50 -8
  99. package/lib/shapes/Line.js +116 -20
  100. package/lib/shapes/Path.d.ts +56 -6
  101. package/lib/shapes/Path.js +203 -128
  102. package/lib/shapes/Rect.d.ts +18 -0
  103. package/lib/shapes/Rect.js +36 -0
  104. package/lib/shapes/RegularPolygon.d.ts +22 -0
  105. package/lib/shapes/RegularPolygon.js +70 -0
  106. package/lib/shapes/Ring.d.ts +19 -0
  107. package/lib/shapes/Ring.js +51 -5
  108. package/lib/shapes/Sprite.d.ts +78 -0
  109. package/lib/shapes/Sprite.js +238 -25
  110. package/lib/shapes/Star.d.ts +23 -0
  111. package/lib/shapes/Star.js +62 -0
  112. package/lib/shapes/Text.d.ts +59 -1
  113. package/lib/shapes/Text.js +481 -97
  114. package/lib/shapes/TextPath.d.ts +49 -3
  115. package/lib/shapes/TextPath.js +278 -34
  116. package/lib/shapes/Transformer.d.ts +124 -12
  117. package/lib/shapes/Transformer.js +864 -140
  118. package/lib/shapes/Wedge.d.ts +22 -0
  119. package/lib/shapes/Wedge.js +67 -3
  120. package/lib/skia-backend.js +9 -0
  121. package/lib/types.d.ts +2 -23
  122. package/lib/types.js +1 -21
  123. package/package.json +12 -16
@@ -1,23 +1,83 @@
1
1
  import type { Layer } from './Layer.ts';
2
2
  import type { IFrame, AnimationFn } from './types.ts';
3
+ /**
4
+ * Animation constructor.
5
+ * @constructor
6
+ * @memberof Konva
7
+ * @param {AnimationFn} func function executed on each animation frame. The function is passed a frame object, which contains
8
+ * timeDiff, lastTime, time, and frameRate properties. The timeDiff property is the number of milliseconds that have passed
9
+ * since the last animation frame. The time property is the time in milliseconds that elapsed from the moment the animation started
10
+ * to the current animation frame. The lastTime property is a `time` value from the previous frame. The frameRate property is the current frame rate in frames / second.
11
+ * Return false from function, if you don't need to redraw layer/layers on some frames.
12
+ * @param {Konva.Layer|Array} [layers] layer(s) to be redrawn on each animation frame. Can be a layer, an array of layers, or null.
13
+ * Not specifying a node will result in no redraw.
14
+ * @example
15
+ * // move a node to the right at 50 pixels / second
16
+ * var velocity = 50;
17
+ *
18
+ * var anim = new Konva.Animation(function(frame) {
19
+ * var dist = velocity * (frame.timeDiff / 1000);
20
+ * node.move({x: dist, y: 0});
21
+ * }, layer);
22
+ *
23
+ * anim.start();
24
+ */
3
25
  export declare class Animation {
4
26
  func: AnimationFn;
5
27
  id: number;
6
28
  layers: Layer[];
7
29
  frame: IFrame;
8
30
  constructor(func: AnimationFn, layers?: any);
31
+ /**
32
+ * set layers to be redrawn on each animation frame
33
+ * @method
34
+ * @name Konva.Animation#setLayers
35
+ * @param {Konva.Layer|Array} [layers] layer(s) to be redrawn. Can be a layer, an array of layers, or null. Not specifying a node will result in no redraw.
36
+ * @return {Konva.Animation} this
37
+ */
9
38
  setLayers(layers: null | Layer | Layer[]): this;
39
+ /**
40
+ * get layers
41
+ * @method
42
+ * @name Konva.Animation#getLayers
43
+ * @return {Array} Array of Konva.Layer
44
+ */
10
45
  getLayers(): Layer[];
46
+ /**
47
+ * add layer. Returns true if the layer was added, and false if it was not
48
+ * @method
49
+ * @name Konva.Animation#addLayer
50
+ * @param {Konva.Layer} layer to add
51
+ * @return {Bool} true if layer is added to animation, otherwise false
52
+ */
11
53
  addLayer(layer: Layer): boolean;
54
+ /**
55
+ * determine if animation is running or not. returns true or false
56
+ * @method
57
+ * @name Konva.Animation#isRunning
58
+ * @return {Bool} is animation running?
59
+ */
12
60
  isRunning(): boolean;
61
+ /**
62
+ * start animation
63
+ * @method
64
+ * @name Konva.Animation#start
65
+ * @return {Konva.Animation} this
66
+ */
13
67
  start(): this;
68
+ /**
69
+ * stop animation
70
+ * @method
71
+ * @name Konva.Animation#stop
72
+ * @return {Konva.Animation} this
73
+ */
14
74
  stop(): this;
15
75
  _updateFrameObject(time: number): void;
16
- static animations: Array<Animation>;
76
+ static animations: Set<Animation>;
17
77
  static animIdCounter: number;
18
78
  static animRunning: boolean;
19
- static _addAnimation(anim: any): void;
20
- static _removeAnimation(anim: any): void;
79
+ static _addAnimation(anim: Animation): void;
80
+ static _removeAnimation(anim: Animation): void;
21
81
  static _runFrames(): void;
22
82
  static _animationLoop(): void;
23
83
  static _handleAnimation(): void;
package/lib/Animation.js CHANGED
@@ -1,15 +1,31 @@
1
+ var _a;
1
2
  import { glob } from "./Global.js";
2
3
  import { Util } from "./Util.js";
3
- const now = (function () {
4
- if (glob.performance && glob.performance.now) {
5
- return function () {
6
- return glob.performance.now();
7
- };
8
- }
9
- return function () {
10
- return new Date().getTime();
11
- };
12
- })();
4
+ const now = ((_a = glob.performance) === null || _a === void 0 ? void 0 : _a.now)
5
+ ? () => glob.performance.now()
6
+ : Date.now;
7
+ /**
8
+ * Animation constructor.
9
+ * @constructor
10
+ * @memberof Konva
11
+ * @param {AnimationFn} func function executed on each animation frame. The function is passed a frame object, which contains
12
+ * timeDiff, lastTime, time, and frameRate properties. The timeDiff property is the number of milliseconds that have passed
13
+ * since the last animation frame. The time property is the time in milliseconds that elapsed from the moment the animation started
14
+ * to the current animation frame. The lastTime property is a `time` value from the previous frame. The frameRate property is the current frame rate in frames / second.
15
+ * Return false from function, if you don't need to redraw layer/layers on some frames.
16
+ * @param {Konva.Layer|Array} [layers] layer(s) to be redrawn on each animation frame. Can be a layer, an array of layers, or null.
17
+ * Not specifying a node will result in no redraw.
18
+ * @example
19
+ * // move a node to the right at 50 pixels / second
20
+ * var velocity = 50;
21
+ *
22
+ * var anim = new Konva.Animation(function(frame) {
23
+ * var dist = velocity * (frame.timeDiff / 1000);
24
+ * node.move({x: dist, y: 0});
25
+ * }, layer);
26
+ *
27
+ * anim.start();
28
+ */
13
29
  export class Animation {
14
30
  constructor(func, layers) {
15
31
  this.id = Animation.animIdCounter++;
@@ -22,20 +38,38 @@ export class Animation {
22
38
  this.func = func;
23
39
  this.setLayers(layers);
24
40
  }
41
+ /**
42
+ * set layers to be redrawn on each animation frame
43
+ * @method
44
+ * @name Konva.Animation#setLayers
45
+ * @param {Konva.Layer|Array} [layers] layer(s) to be redrawn. Can be a layer, an array of layers, or null. Not specifying a node will result in no redraw.
46
+ * @return {Konva.Animation} this
47
+ */
25
48
  setLayers(layers) {
26
- let lays = [];
27
- if (layers) {
28
- lays = Array.isArray(layers) ? layers : [layers];
29
- }
30
- this.layers = lays;
49
+ // a copy, so that addLayer() never pushes into the caller's array
50
+ this.layers = layers ? [].concat(layers) : [];
31
51
  return this;
32
52
  }
53
+ /**
54
+ * get layers
55
+ * @method
56
+ * @name Konva.Animation#getLayers
57
+ * @return {Array} Array of Konva.Layer
58
+ */
33
59
  getLayers() {
34
60
  return this.layers;
35
61
  }
62
+ /**
63
+ * add layer. Returns true if the layer was added, and false if it was not
64
+ * @method
65
+ * @name Konva.Animation#addLayer
66
+ * @param {Konva.Layer} layer to add
67
+ * @return {Bool} true if layer is added to animation, otherwise false
68
+ */
36
69
  addLayer(layer) {
37
70
  const layers = this.layers;
38
71
  const len = layers.length;
72
+ // don't add the layer if it already exists
39
73
  for (let n = 0; n < len; n++) {
40
74
  if (layers[n]._id === layer._id) {
41
75
  return false;
@@ -44,17 +78,21 @@ export class Animation {
44
78
  this.layers.push(layer);
45
79
  return true;
46
80
  }
81
+ /**
82
+ * determine if animation is running or not. returns true or false
83
+ * @method
84
+ * @name Konva.Animation#isRunning
85
+ * @return {Bool} is animation running?
86
+ */
47
87
  isRunning() {
48
- const a = Animation;
49
- const animations = a.animations;
50
- const len = animations.length;
51
- for (let n = 0; n < len; n++) {
52
- if (animations[n].id === this.id) {
53
- return true;
54
- }
55
- }
56
- return false;
88
+ return Animation.animations.has(this);
57
89
  }
90
+ /**
91
+ * start animation
92
+ * @method
93
+ * @name Konva.Animation#start
94
+ * @return {Konva.Animation} this
95
+ */
58
96
  start() {
59
97
  this.stop();
60
98
  this.frame.timeDiff = 0;
@@ -62,6 +100,12 @@ export class Animation {
62
100
  Animation._addAnimation(this);
63
101
  return this;
64
102
  }
103
+ /**
104
+ * stop animation
105
+ * @method
106
+ * @name Konva.Animation#stop
107
+ * @return {Konva.Animation} this
108
+ */
65
109
  stop() {
66
110
  Animation._removeAnimation(this);
67
111
  return this;
@@ -73,56 +117,33 @@ export class Animation {
73
117
  this.frame.frameRate = 1000 / this.frame.timeDiff;
74
118
  }
75
119
  static _addAnimation(anim) {
76
- this.animations.push(anim);
120
+ this.animations.add(anim);
77
121
  this._handleAnimation();
78
122
  }
79
123
  static _removeAnimation(anim) {
80
- const id = anim.id;
81
- const animations = this.animations;
82
- const len = animations.length;
83
- for (let n = 0; n < len; n++) {
84
- if (animations[n].id === id) {
85
- this.animations.splice(n, 1);
86
- break;
87
- }
88
- }
124
+ this.animations.delete(anim);
89
125
  }
90
126
  static _runFrames() {
91
- const layerHash = {};
92
- const animations = this.animations;
93
- for (let n = 0; n < animations.length; n++) {
94
- const anim = animations[n];
95
- const layers = anim.layers;
96
- const func = anim.func;
97
- anim._updateFrameObject(now());
98
- const layersLen = layers.length;
99
- let needRedraw;
100
- if (func) {
101
- needRedraw = func.call(anim, anim.frame) !== false;
102
- }
103
- else {
104
- needRedraw = true;
105
- }
106
- if (!needRedraw) {
107
- continue;
127
+ // every layer is drawn once, however many animations touch it
128
+ const layersToDraw = new Set();
129
+ // an animation may stop or restart itself, or another one, inside its
130
+ // function: each one runs at most once per frame, a stopped one not at all
131
+ Array.from(this.animations).forEach((anim) => {
132
+ if (!this.animations.has(anim)) {
133
+ return;
108
134
  }
109
- for (let i = 0; i < layersLen; i++) {
110
- const layer = layers[i];
111
- if (layer._id !== undefined) {
112
- layerHash[layer._id] = layer;
113
- }
114
- }
115
- }
116
- for (const key in layerHash) {
117
- if (!layerHash.hasOwnProperty(key)) {
118
- continue;
135
+ anim._updateFrameObject(now());
136
+ // the function returns false to skip the redraw
137
+ if (anim.func && anim.func.call(anim, anim.frame) === false) {
138
+ return;
119
139
  }
120
- layerHash[key].batchDraw();
121
- }
140
+ anim.layers.forEach((layer) => layer && layersToDraw.add(layer));
141
+ });
142
+ layersToDraw.forEach((layer) => layer.batchDraw());
122
143
  }
123
144
  static _animationLoop() {
124
145
  const Anim = Animation;
125
- if (Anim.animations.length) {
146
+ if (Anim.animations.size) {
126
147
  Anim._runFrames();
127
148
  Util.requestAnimFrame(Anim._animationLoop);
128
149
  }
@@ -137,6 +158,6 @@ export class Animation {
137
158
  }
138
159
  }
139
160
  }
140
- Animation.animations = [];
161
+ Animation.animations = new Set();
141
162
  Animation.animIdCounter = 0;
142
163
  Animation.animRunning = false;
@@ -4,5 +4,15 @@ export declare const binomialCoefficients: number[][];
4
4
  export declare const getCubicArcLength: (xs: number[], ys: number[], t: number) => number;
5
5
  export declare const getQuadraticArcLength: (xs: number[], ys: number[], t: number) => number;
6
6
  export declare const t2length: (length: number, totalLength: number, func: (t: number) => number) => number;
7
+ /**
8
+ * Points where a quadratic bezier segment reaches its highest or lowest value
9
+ * on one of the two axes, as a flat [x, y, x, y, ...] list. The two end points
10
+ * are not included, because the caller knows them already.
11
+ */
7
12
  export declare const getQuadraticExtremaPoints: (x0: number, y0: number, x1: number, y1: number, x2: number, y2: number) => number[];
13
+ /**
14
+ * Points where a cubic bezier segment reaches its highest or lowest value on
15
+ * one of the two axes, as a flat [x, y, x, y, ...] list. The two end points
16
+ * are not included, because the caller knows them already.
17
+ */
8
18
  export declare const getCubicExtremaPoints: (x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number) => number[];
@@ -1,3 +1,5 @@
1
+ // Credits: rveciana/svg-path-properties
2
+ // Legendre-Gauss abscissae (xi values, defined at i=n as the roots of the nth order Legendre polynomial Pn(x))
1
3
  export const tValues = [
2
4
  [],
3
5
  [],
@@ -336,6 +338,7 @@ export const tValues = [
336
338
  0.9951872199970213601799974097007368118745,
337
339
  ],
338
340
  ];
341
+ // Legendre-Gauss weights (wi values, defined by a function linked to in the Bezier primer article)
339
342
  export const cValues = [
340
343
  [],
341
344
  [],
@@ -682,10 +685,14 @@ export const cValues = [
682
685
  0.0123412297999871995468056670700372915759,
683
686
  ],
684
687
  ];
688
+ // LUT for binomial coefficient arrays per curve order 'n'
685
689
  export const binomialCoefficients = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]];
686
690
  export const getCubicArcLength = (xs, ys, t) => {
687
691
  let sum;
688
692
  let correctedT;
693
+ /*if (xs.length >= tValues.length) {
694
+ throw new Error('too high n bezier');
695
+ }*/
689
696
  const n = 20;
690
697
  const z = t / 2;
691
698
  sum = 0;
@@ -726,13 +733,18 @@ function BFunc(xs, ys, t) {
726
733
  const combined = xbase * xbase + ybase * ybase;
727
734
  return Math.sqrt(combined);
728
735
  }
736
+ /**
737
+ * Compute the curve derivative (hodograph) at t.
738
+ */
729
739
  const getDerivative = (derivative, t, vs) => {
740
+ // the derivative of any 't'-less function is zero.
730
741
  const n = vs.length - 1;
731
742
  let _vs;
732
743
  let value;
733
744
  if (n === 0) {
734
745
  return 0;
735
746
  }
747
+ // direct values? compute!
736
748
  if (derivative === 0) {
737
749
  value = 0;
738
750
  for (let k = 0; k <= n; k++) {
@@ -745,6 +757,8 @@ const getDerivative = (derivative, t, vs) => {
745
757
  return value;
746
758
  }
747
759
  else {
760
+ // Still some derivative? go down one order, then try
761
+ // for the lower order curve's.
748
762
  _vs = new Array(n);
749
763
  for (let k = 0; k < n; k++) {
750
764
  _vs[k] = n * (vs[k + 1] - vs[k]);
@@ -786,12 +800,20 @@ const quadraticAt = (p0, p1, p2, t) => {
786
800
  const mt = 1 - t;
787
801
  return mt * mt * p0 + 2 * mt * t * p1 + t * t * p2;
788
802
  };
803
+ /**
804
+ * Points where a quadratic bezier segment reaches its highest or lowest value
805
+ * on one of the two axes, as a flat [x, y, x, y, ...] list. The two end points
806
+ * are not included, because the caller knows them already.
807
+ */
789
808
  export const getQuadraticExtremaPoints = (x0, y0, x1, y1, x2, y2) => {
790
809
  const extrema = [];
791
810
  for (const axis of [
792
811
  [x0, x1, x2],
793
812
  [y0, y1, y2],
794
813
  ]) {
814
+ // the derivative of the quadratic is linear, so it has one root. A straight
815
+ // segment makes the denominator 0, and the division then gives a value that
816
+ // is not in the range below.
795
817
  const t = (axis[0] - axis[1]) / (axis[0] - 2 * axis[1] + axis[2]);
796
818
  if (t > 0 && t < 1) {
797
819
  extrema.push(quadraticAt(x0, x1, x2, t), quadraticAt(y0, y1, y2, t));
@@ -806,12 +828,18 @@ const cubicAt = (p0, p1, p2, p3, t) => {
806
828
  3 * mt * t * t * p2 +
807
829
  t * t * t * p3);
808
830
  };
831
+ /**
832
+ * Points where a cubic bezier segment reaches its highest or lowest value on
833
+ * one of the two axes, as a flat [x, y, x, y, ...] list. The two end points
834
+ * are not included, because the caller knows them already.
835
+ */
809
836
  export const getCubicExtremaPoints = (x0, y0, x1, y1, x2, y2, x3, y3) => {
810
837
  const extrema = [];
811
838
  for (const axis of [
812
839
  [x0, x1, x2, x3],
813
840
  [y0, y1, y2, y3],
814
841
  ]) {
842
+ // the derivative of the cubic is a * t * t + b * t + c
815
843
  const a = -3 * axis[0] + 9 * axis[1] - 9 * axis[2] + 3 * axis[3];
816
844
  const b = 6 * axis[0] - 12 * axis[1] + 6 * axis[2];
817
845
  const c = -3 * axis[0] + 3 * axis[1];
@@ -819,6 +847,10 @@ export const getCubicExtremaPoints = (x0, y0, x1, y1, x2, y2, x3, y3) => {
819
847
  if (discriminant < 0) {
820
848
  continue;
821
849
  }
850
+ // stable form of the quadratic formula. The plain (-b +- d) / (2 * a)
851
+ // loses the root that stays finite when a is zero or near zero, which is
852
+ // what a symmetric pair of control points gives. Roots that are not
853
+ // finite fall out of the range test below.
822
854
  const q = -(b + (b < 0 ? -1 : 1) * Math.sqrt(discriminant)) / 2;
823
855
  for (const t of [q / a, c / q]) {
824
856
  if (t > 0 && t < 1) {
package/lib/Canvas.d.ts CHANGED
@@ -5,23 +5,76 @@ interface ICanvasConfig {
5
5
  pixelRatio?: number;
6
6
  willReadFrequently?: boolean;
7
7
  }
8
+ /**
9
+ * Canvas Renderer constructor. It is a wrapper around native canvas element.
10
+ * Usually you don't need to use it manually.
11
+ * @constructor
12
+ * @abstract
13
+ * @memberof Konva
14
+ * @param {Object} config
15
+ * @param {Number} config.width
16
+ * @param {Number} config.height
17
+ * @param {Number} config.pixelRatio
18
+ */
8
19
  export declare class Canvas {
9
20
  pixelRatio: number;
10
21
  _canvas: HTMLCanvasElement;
11
22
  context: Context;
12
23
  width: number;
13
24
  height: number;
25
+ _logicalWidth: number;
26
+ _logicalHeight: number;
14
27
  isCache: boolean;
28
+ x: number;
29
+ y: number;
15
30
  constructor(config: ICanvasConfig);
31
+ /**
32
+ * get canvas context
33
+ * @method
34
+ * @name Konva.Canvas#getContext
35
+ * @returns {CanvasContext} context
36
+ */
16
37
  getContext(): Context;
38
+ /**
39
+ * get pixel ratio
40
+ * @method
41
+ * @name Konva.Canvas#getPixelRatio
42
+ * @returns {Number} pixel ratio
43
+ * @example
44
+ * var pixelRatio = layer.getCanvas.getPixelRatio();
45
+ */
17
46
  getPixelRatio(): number;
47
+ /**
48
+ * set pixel ratio
49
+ * KonvaJS automatically handles pixel ratio adustments in order to render crisp drawings
50
+ * on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios
51
+ * of 1. Some high end tablets and phones, like iPhones and iPads have a device pixel ratio
52
+ * of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel
53
+ * ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise
54
+ * specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel
55
+ * ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1.
56
+ * @method
57
+ * @name Konva.Canvas#setPixelRatio
58
+ * @param {Number} pixelRatio
59
+ * @example
60
+ * layer.getCanvas().setPixelRatio(3);
61
+ */
18
62
  setPixelRatio(pixelRatio: any): void;
19
63
  setWidth(width: any): void;
20
64
  setHeight(height: any): void;
21
65
  getWidth(): number;
22
66
  getHeight(): number;
67
+ _bitmapSize(size: number): number;
23
68
  setSize(width: any, height: any): void;
24
69
  setSizeIfChanged(width: number, height: number): void;
70
+ /**
71
+ * to data url
72
+ * @method
73
+ * @name Konva.Canvas#toDataURL
74
+ * @param {String} mimeType
75
+ * @param {Number} quality between 0 and 1 for jpg mime types
76
+ * @returns {String} data url string
77
+ */
25
78
  toDataURL(mimeType: any, quality: any): string;
26
79
  }
27
80
  export declare class SceneCanvas extends Canvas {
package/lib/Canvas.js CHANGED
@@ -1,35 +1,40 @@
1
1
  import { Util } from "./Util.js";
2
2
  import { SceneContext, HitContext } from "./Context.js";
3
3
  import { Konva } from "./Global.js";
4
- let _pixelRatio;
5
- function getDevicePixelRatio() {
6
- if (_pixelRatio) {
7
- return _pixelRatio;
8
- }
9
- const canvas = Util.createCanvasElement();
10
- const context = canvas.getContext('2d');
11
- _pixelRatio = (function () {
12
- const devicePixelRatio = Konva._global.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio ||
13
- context.mozBackingStorePixelRatio ||
14
- context.msBackingStorePixelRatio ||
15
- context.oBackingStorePixelRatio ||
16
- context.backingStorePixelRatio ||
17
- 1;
18
- return devicePixelRatio / backingStoreRatio;
19
- })();
20
- Util.releaseCanvas(canvas);
21
- return _pixelRatio;
22
- }
4
+ /**
5
+ * Canvas Renderer constructor. It is a wrapper around native canvas element.
6
+ * Usually you don't need to use it manually.
7
+ * @constructor
8
+ * @abstract
9
+ * @memberof Konva
10
+ * @param {Object} config
11
+ * @param {Number} config.width
12
+ * @param {Number} config.height
13
+ * @param {Number} config.pixelRatio
14
+ */
23
15
  export class Canvas {
24
16
  constructor(config) {
25
17
  this.pixelRatio = 1;
18
+ // the bitmap size, in device pixels
26
19
  this.width = 0;
27
20
  this.height = 0;
21
+ // the size the canvas was given, in CSS pixels; the bitmap truncates it
22
+ this._logicalWidth = 0;
23
+ this._logicalHeight = 0;
28
24
  this.isCache = false;
25
+ // origin of a buffer canvas in the coordinate space of the canvas it is
26
+ // drawn back into, see Shape.drawScene
27
+ this.x = 0;
28
+ this.y = 0;
29
29
  const conf = config || {};
30
- const pixelRatio = conf.pixelRatio || Konva.pixelRatio || getDevicePixelRatio();
30
+ // a Konva.pixelRatio reset to undefined or 0 means the device ratio
31
+ const pixelRatio = conf.pixelRatio ||
32
+ Konva.pixelRatio ||
33
+ Konva._global.devicePixelRatio ||
34
+ 1;
31
35
  this.pixelRatio = pixelRatio;
32
36
  this._canvas = Util.createCanvasElement();
37
+ // set inline styles
33
38
  this._canvas.style.padding = '0';
34
39
  this._canvas.style.margin = '0';
35
40
  this._canvas.style.border = '0';
@@ -38,28 +43,50 @@ export class Canvas {
38
43
  this._canvas.style.top = '0';
39
44
  this._canvas.style.left = '0';
40
45
  }
46
+ /**
47
+ * get canvas context
48
+ * @method
49
+ * @name Konva.Canvas#getContext
50
+ * @returns {CanvasContext} context
51
+ */
41
52
  getContext() {
42
53
  return this.context;
43
54
  }
55
+ /**
56
+ * get pixel ratio
57
+ * @method
58
+ * @name Konva.Canvas#getPixelRatio
59
+ * @returns {Number} pixel ratio
60
+ * @example
61
+ * var pixelRatio = layer.getCanvas.getPixelRatio();
62
+ */
44
63
  getPixelRatio() {
45
64
  return this.pixelRatio;
46
65
  }
66
+ /**
67
+ * set pixel ratio
68
+ * KonvaJS automatically handles pixel ratio adustments in order to render crisp drawings
69
+ * on all devices. Most desktops, low end tablets, and low end phones, have device pixel ratios
70
+ * of 1. Some high end tablets and phones, like iPhones and iPads have a device pixel ratio
71
+ * of 2. Some Macbook Pros, and iMacs also have a device pixel ratio of 2. Some high end Android devices have pixel
72
+ * ratios of 2 or 3. Some browsers like Firefox allow you to configure the pixel ratio of the viewport. Unless otherwise
73
+ * specificed, the pixel ratio will be defaulted to the actual device pixel ratio. You can override the device pixel
74
+ * ratio for special situations, or, if you don't want the pixel ratio to be taken into account, you can set it to 1.
75
+ * @method
76
+ * @name Konva.Canvas#setPixelRatio
77
+ * @param {Number} pixelRatio
78
+ * @example
79
+ * layer.getCanvas().setPixelRatio(3);
80
+ */
47
81
  setPixelRatio(pixelRatio) {
48
- const previousRatio = this.pixelRatio;
49
82
  this.pixelRatio = pixelRatio;
50
- this.setSize(this.getWidth() / previousRatio, this.getHeight() / previousRatio);
83
+ this.setSize(this._logicalWidth, this._logicalHeight);
51
84
  }
52
85
  setWidth(width) {
53
- this.width = this._canvas.width = width * this.pixelRatio;
54
- this._canvas.style.width = width + 'px';
55
- const pixelRatio = this.pixelRatio, _context = this.getContext()._context;
56
- _context.scale(pixelRatio, pixelRatio);
86
+ this.setSize(width, this._logicalHeight);
57
87
  }
58
88
  setHeight(height) {
59
- this.height = this._canvas.height = height * this.pixelRatio;
60
- this._canvas.style.height = height + 'px';
61
- const pixelRatio = this.pixelRatio, _context = this.getContext()._context;
62
- _context.scale(pixelRatio, pixelRatio);
89
+ this.setSize(this._logicalWidth, height);
63
90
  }
64
91
  getWidth() {
65
92
  return this.width;
@@ -67,18 +94,50 @@ export class Canvas {
67
94
  getHeight() {
68
95
  return this.height;
69
96
  }
97
+ // the bitmap holds whole pixels: a fractional pixel ratio truncates, and
98
+ // a size that does not match the bitmap would resample every draw of it
99
+ _bitmapSize(size) {
100
+ return Math.floor((size || 0) * this.pixelRatio);
101
+ }
70
102
  setSize(width, height) {
71
- this.setWidth(width || 0);
72
- this.setHeight(height || 0);
103
+ // a NaN or Infinity size would silently give an empty bitmap
104
+ if (!isFinite(width !== null && width !== void 0 ? width : 0) || !isFinite(height !== null && height !== void 0 ? height : 0)) {
105
+ Util.error(`Canvas size must be finite numbers, got ${width}x${height}. The canvas is left empty.`);
106
+ width = height = 0;
107
+ }
108
+ width = width || 0;
109
+ height = height || 0;
110
+ const pixelRatio = this.pixelRatio;
111
+ this._logicalWidth = width;
112
+ this._logicalHeight = height;
113
+ // take into account pixel ratio. Assigning a dimension reallocates the
114
+ // bitmap and resets the whole context state, so scale once after both
115
+ this.width = this._canvas.width = this._bitmapSize(width);
116
+ this.height = this._canvas.height = this._bitmapSize(height);
117
+ this._canvas.style.width = width + 'px';
118
+ this._canvas.style.height = height + 'px';
119
+ this.getContext()._context.scale(pixelRatio, pixelRatio);
73
120
  }
121
+ // setSize() re-allocates and clears the canvas even for the same size,
122
+ // so lazily sized canvases use this to stay untouched when nothing changed
74
123
  setSizeIfChanged(width, height) {
75
- if (this.width !== width * this.pixelRatio ||
76
- this.height !== height * this.pixelRatio) {
124
+ if (this.width !== this._bitmapSize(width) ||
125
+ this.height !== this._bitmapSize(height)) {
77
126
  this.setSize(width, height);
78
127
  }
79
128
  }
129
+ /**
130
+ * to data url
131
+ * @method
132
+ * @name Konva.Canvas#toDataURL
133
+ * @param {String} mimeType
134
+ * @param {Number} quality between 0 and 1 for jpg mime types
135
+ * @returns {String} data url string
136
+ */
80
137
  toDataURL(mimeType, quality) {
81
138
  try {
139
+ // If this call fails (due to browser bug, like in Firefox 3.6),
140
+ // then revert to previous no-parameter image/png behavior
82
141
  return this._canvas.toDataURL(mimeType, quality);
83
142
  }
84
143
  catch (e) {