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
package/lib/Node.js CHANGED
@@ -1,11 +1,14 @@
1
1
  import { HitCanvas, SceneCanvas } from "./Canvas.js";
2
2
  import { isCSSFiltersSupported } from "./Context.js";
3
3
  import { DD } from "./DragAndDrop.js";
4
+ import * as PointerEvents from "./PointerEvents.js";
4
5
  import { Factory } from "./Factory.js";
5
6
  import { Konva } from "./Global.js";
6
7
  import { Transform, Util } from "./Util.js";
7
8
  import { getBooleanValidator, getNumberValidator, getStringValidator, } from "./Validators.js";
9
+ // CSS filter parser for fallback to function filters
8
10
  function parseCSSFilters(cssFilter) {
11
+ // Parse common CSS filter functions and map to Konva filters
9
12
  const filterRegex = /(\w+)\(([^)]+)\)/g;
10
13
  let match;
11
14
  while ((match = filterRegex.exec(cssFilter)) !== null) {
@@ -14,7 +17,10 @@ function parseCSSFilters(cssFilter) {
14
17
  case 'blur': {
15
18
  const blurRadius = parseFloat(filterValue.replace('px', ''));
16
19
  return function (imageData) {
20
+ // CSS blur uses standard deviation, Stack Blur uses radius
21
+ // Empirical testing shows CSS blur needs ~0.5 scaling for visual match
17
22
  this.blurRadius(blurRadius * 0.5);
23
+ // Access filters through dynamic import to avoid circular dependency
18
24
  const KonvaFilters = Konva.Filters;
19
25
  if (KonvaFilters && KonvaFilters.Blur) {
20
26
  KonvaFilters.Blur.call(this, imageData);
@@ -26,7 +32,7 @@ function parseCSSFilters(cssFilter) {
26
32
  ? parseFloat(filterValue) / 100
27
33
  : parseFloat(filterValue);
28
34
  return function (imageData) {
29
- this.brightness(brightness);
35
+ this.brightness(brightness); // CSS uses multiplier
30
36
  const KonvaFilters = Konva.Filters;
31
37
  if (KonvaFilters && KonvaFilters.Brightness) {
32
38
  KonvaFilters.Brightness.call(this, imageData);
@@ -36,6 +42,8 @@ function parseCSSFilters(cssFilter) {
36
42
  case 'contrast': {
37
43
  const contrast = parseFloat(filterValue);
38
44
  return function (imageData) {
45
+ // Convert CSS contrast to Konva parameter using square root conversion
46
+ // to account for Konva's quadratic scaling: Math.pow((param + 100) / 100, 2)
39
47
  const konvaContrast = 100 * (Math.sqrt(contrast) - 1);
40
48
  this.contrast(konvaContrast);
41
49
  const KonvaFilters = Konva.Filters;
@@ -75,7 +83,15 @@ function parseCSSFilters(cssFilter) {
75
83
  }
76
84
  return () => { };
77
85
  }
78
- const ABSOLUTE_OPACITY = 'absoluteOpacity', ALL_LISTENERS = 'allEventListeners', ABSOLUTE_TRANSFORM = 'absoluteTransform', ABSOLUTE_SCALE = 'absoluteScale', CANVAS = 'canvas', CHANGE = 'Change', CHILDREN = 'children', KONVA = 'konva', LISTENING = 'listening', MOUSEENTER = 'mouseenter', MOUSELEAVE = 'mouseleave', POINTERENTER = 'pointerenter', POINTERLEAVE = 'pointerleave', TOUCHENTER = 'touchenter', TOUCHLEAVE = 'touchleave', NAME = 'name', SET = 'set', SHAPE = 'Shape', SPACE = ' ', STAGE = 'stage', TRANSFORM = 'transform', UPPER_STAGE = 'Stage', VISIBLE = 'visible', TRANSFORM_CHANGE_STR = [
86
+ // CONSTANTS
87
+ const ABSOLUTE_OPACITY = 'absoluteOpacity', ABSOLUTE_TRANSFORM = 'absoluteTransform', CHANGE = 'Change', CHILDREN = 'children', KONVA = 'konva', LISTENING = 'listening', MOUSEENTER = 'mouseenter', MOUSELEAVE = 'mouseleave', POINTERENTER = 'pointerenter', POINTERLEAVE = 'pointerleave', TOUCHENTER = 'touchenter', TOUCHLEAVE = 'touchleave', NON_BUBBLING_EVENTS = [
88
+ MOUSEENTER,
89
+ MOUSELEAVE,
90
+ POINTERENTER,
91
+ POINTERLEAVE,
92
+ TOUCHENTER,
93
+ TOUCHLEAVE,
94
+ ], SET = 'set', SHAPE = 'Shape', SPACE = ' ', STAGE = 'stage', TRANSFORM = 'transform', UPPER_STAGE = 'Stage', VISIBLE = 'visible', TRANSFORM_CHANGE_STR = [
79
95
  'xChange.konva',
80
96
  'yChange.konva',
81
97
  'scaleXChange.konva',
@@ -88,66 +104,105 @@ const ABSOLUTE_OPACITY = 'absoluteOpacity', ALL_LISTENERS = 'allEventListeners',
88
104
  'transformsEnabledChange.konva',
89
105
  ].join(SPACE);
90
106
  let idCounter = 1;
107
+ // "perfect drawing" buffer for cache() and toCanvas(): it mirrors the target
108
+ // canvas and is drawn back at (x, y) in the target's coordinate space.
109
+ // It starts empty and Shape.drawScene sizes it on first use, so nodes
110
+ // without buffered shapes never allocate it.
111
+ function createBufferCanvas(target, x, y) {
112
+ const bufferCanvas = new SceneCanvas({
113
+ width: 0,
114
+ height: 0,
115
+ pixelRatio: target.pixelRatio,
116
+ });
117
+ bufferCanvas.x = x;
118
+ bufferCanvas.y = y;
119
+ return bufferCanvas;
120
+ }
121
+ /**
122
+ * Node constructor. Nodes are entities that can be transformed, layered,
123
+ * and have bound events. The stage, layers, groups, and shapes all extend Node.
124
+ * @constructor
125
+ * @memberof Konva
126
+ * @param {Object} config
127
+ * @@nodeParams
128
+ */
91
129
  export class Node {
92
130
  constructor(config) {
93
131
  this._id = idCounter++;
94
132
  this.eventListeners = {};
95
133
  this.attrs = {};
96
134
  this.index = 0;
97
- this._allEventListeners = null;
98
135
  this.parent = null;
99
- this._cache = new Map();
100
- this._attachedDepsListeners = new Map();
101
- this._lastPos = null;
136
+ // derived values (transforms, visibility, opacity...), see _getCache()
137
+ this._cache = {};
138
+ // canvases of cache(), see _getCanvasCache()
139
+ this._canvasCache = null;
102
140
  this._batchingTransformChange = false;
103
141
  this._needClearTransformCache = false;
104
142
  this._filterUpToDate = false;
105
143
  this._isUnderCache = false;
106
144
  this._dragEventId = null;
107
145
  this._shouldFireChangeEvents = false;
146
+ // on initial set attrs wi don't need to fire change events
147
+ // because nobody is listening to them yet
108
148
  this.setAttrs(config);
109
149
  this._shouldFireChangeEvents = true;
150
+ // all change event listeners are attached to the prototype
110
151
  }
111
152
  hasChildren() {
112
153
  return false;
113
154
  }
114
155
  _clearCache(attr) {
156
+ // if we want to clear transform cache
157
+ // we don't really need to remove it from the cache
158
+ // but instead mark as "dirty"
159
+ // so we don't need to create a new instance next time
115
160
  if ((attr === TRANSFORM || attr === ABSOLUTE_TRANSFORM) &&
116
- this._cache.get(attr)) {
117
- this._cache.get(attr).dirty = true;
161
+ this._cache[attr]) {
162
+ this._cache[attr].dirty = true;
118
163
  }
119
164
  else if (attr) {
120
- this._cache.delete(attr);
165
+ this._cache[attr] = undefined;
121
166
  }
122
167
  else {
123
- this._cache.clear();
168
+ this._cache = {};
169
+ // clearCache() also reaches descendants whose ancestor transform changes
170
+ // were suppressed while cached. Invalidate their saved Transformer bounds.
171
+ if (this._attrsVersion !== undefined)
172
+ this._attrsVersion++;
173
+ }
174
+ }
175
+ // drop the cached canvases and give their memory back
176
+ _releaseCanvasCache() {
177
+ const cache = this._canvasCache;
178
+ if (cache) {
179
+ Util.releaseCanvas(cache.scene._canvas, cache.filter._canvas, ...(cache.hit ? [cache.hit._canvas] : []));
180
+ this._canvasCache = null;
124
181
  }
125
182
  }
126
183
  _getCache(attr, privateGetter) {
127
- let cache = this._cache.get(attr);
184
+ let cache = this._cache[attr];
185
+ // for transform the cache can be NOT empty
186
+ // but we still need to recalculate it if it is dirty
128
187
  const isTransform = attr === TRANSFORM || attr === ABSOLUTE_TRANSFORM;
129
188
  const invalid = cache === undefined || (isTransform && cache.dirty === true);
189
+ // if not cached, we need to set it using the private getter method.
130
190
  if (invalid) {
131
191
  cache = privateGetter.call(this);
132
- this._cache.set(attr, cache);
192
+ this._cache[attr] = cache;
133
193
  }
134
194
  return cache;
135
195
  }
136
- _calculate(name, deps, getter) {
137
- if (!this._attachedDepsListeners.get(name)) {
138
- const depsString = deps.map((dep) => dep + 'Change.konva').join(SPACE);
139
- this.on(depsString, () => {
140
- this._clearCache(name);
141
- });
142
- this._attachedDepsListeners.set(name, true);
143
- }
144
- return this._getCache(name, getter);
145
- }
146
196
  _getCanvasCache() {
147
- return this._cache.get(CANVAS);
197
+ return this._canvasCache;
148
198
  }
199
+ /*
200
+ * when the logic for a cached result depends on ancestor propagation, use this
201
+ * method to clear self and children cache
202
+ */
149
203
  _clearSelfAndDescendantCache(attr) {
150
204
  this._clearCache(attr);
205
+ // trigger clear cache, so transformer can use it
151
206
  if (attr === ABSOLUTE_TRANSFORM) {
152
207
  this.fire('absoluteTransformChange');
153
208
  }
@@ -160,19 +215,69 @@ export class Node {
160
215
  cb();
161
216
  }
162
217
  }
218
+ /**
219
+ * clear cached canvas
220
+ * @method
221
+ * @name Konva.Node#clearCache
222
+ * @returns {Konva.Node}
223
+ * @example
224
+ * node.clearCache();
225
+ */
163
226
  clearCache() {
164
- if (this._cache.has(CANVAS)) {
165
- const { scene, filter, hit } = this._cache.get(CANVAS);
166
- Util.releaseCanvas(scene._canvas, filter._canvas, ...(hit ? [hit._canvas] : []));
167
- this._cache.delete(CANVAS);
168
- }
227
+ this._releaseCanvasCache();
169
228
  this._clearSelfAndDescendantCache();
170
229
  this._requestDraw();
171
230
  return this;
172
231
  }
232
+ /**
233
+ * cache node to improve drawing performance, apply filters, or create more accurate
234
+ * hit regions. For all basic shapes size of cache canvas will be automatically detected.
235
+ * If you need to cache your custom `Konva.Shape` instance you have to pass shape's bounding box
236
+ * properties. Look at [https://konvajs.org/docs/performance/Shape_Caching.html](https://konvajs.org/docs/performance/Shape_Caching.html) for more information.
237
+ * @method
238
+ * @name Konva.Node#cache
239
+ * @param {Object} [config]
240
+ * @param {Number} [config.x]
241
+ * @param {Number} [config.y]
242
+ * @param {Number} [config.width]
243
+ * @param {Number} [config.height]
244
+ * @param {Number} [config.offset] increase canvas size by `offset` pixel in all directions.
245
+ * @param {Boolean} [config.drawBorder] when set to true, a red border will be drawn around the cached
246
+ * region for debugging purposes
247
+ * @param {Number} [config.pixelRatio] pixel ratio of the cache canvas, the canvas pixels per CSS pixel of the node. Default is `Konva.pixelRatio`, the device pixel ratio. A higher value keeps the cache sharp when the node is scaled up.
248
+ * @param {Boolean} [config.imageSmoothingEnabled] control imageSmoothingEnabled property of created canvas for cache
249
+ * @param {Number} [config.hitCanvasPixelRatio] change quality (or pixel ratio) of cached hit canvas.
250
+ * @returns {Konva.Node}
251
+ * @example
252
+ * // cache a shape with the x,y position of the bounding box at the center and
253
+ * // the width and height of the bounding box equal to the width and height of
254
+ * // the shape obtained from shape.width() and shape.height()
255
+ * image.cache();
256
+ *
257
+ * // cache a node and define the bounding box position and size
258
+ * node.cache({
259
+ * x: -30,
260
+ * y: -30,
261
+ * width: 100,
262
+ * height: 200
263
+ * });
264
+ *
265
+ * // cache a node and draw a red border around the bounding box
266
+ * // for debugging purposes
267
+ * node.cache({
268
+ * x: -30,
269
+ * y: -30,
270
+ * width: 100,
271
+ * height: 200,
272
+ * offset : 10,
273
+ * drawBorder: true
274
+ * });
275
+ */
173
276
  cache(config) {
174
277
  const conf = config || {};
175
278
  let rect = {};
279
+ // don't call getClientRect if we have all attributes
280
+ // it means call it only if have one undefined
176
281
  if (conf.x === undefined ||
177
282
  conf.y === undefined ||
178
283
  conf.width === undefined ||
@@ -183,10 +288,13 @@ export class Node {
183
288
  });
184
289
  }
185
290
  let width = Math.ceil(conf.width || rect.width), height = Math.ceil(conf.height || rect.height), pixelRatio = conf.pixelRatio, x = conf.x === undefined ? Math.floor(rect.x) : conf.x, y = conf.y === undefined ? Math.floor(rect.y) : conf.y, offset = conf.offset || 0, drawBorder = conf.drawBorder || false, hitCanvasPixelRatio = conf.hitCanvasPixelRatio || 1;
186
- if (!width || !height) {
187
- Util.error('Can not cache the node. Width or height of the node equals 0. Caching is skipped.');
188
- return;
291
+ if (!width || !height || !isFinite(x + y + width + height)) {
292
+ Util.error(`Can not cache the node. Its size is 0 or its bounds are not finite numbers (${x}, ${y}, ${width}x${height}). Caching is skipped.`);
293
+ return this;
189
294
  }
295
+ // because using Math.floor on x, y position may shift drawing
296
+ // to avoid shift we need to increase size
297
+ // but we better to avoid it, for better filters flows
190
298
  const extraPaddingX = Math.abs(Math.round(rect.x) - x) > 0.5 ? 1 : 0;
191
299
  const extraPaddingY = Math.abs(Math.round(rect.y) - y) > 0.5 ? 1 : 0;
192
300
  width += offset * 2 + extraPaddingX;
@@ -203,30 +311,36 @@ export class Node {
203
311
  height: 0,
204
312
  willReadFrequently: true,
205
313
  }), sceneContext = cachedSceneCanvas.getContext();
206
- const bufferCanvas = new SceneCanvas({
207
- width: cachedSceneCanvas.width / cachedSceneCanvas.pixelRatio + Math.abs(x),
208
- height: cachedSceneCanvas.height / cachedSceneCanvas.pixelRatio + Math.abs(y),
209
- pixelRatio: cachedSceneCanvas.pixelRatio,
210
- }), bufferContext = bufferCanvas.getContext();
314
+ const bufferCanvas = createBufferCanvas(cachedSceneCanvas, x, y);
211
315
  cachedSceneCanvas.isCache = true;
212
- this._cache.delete(CANVAS);
316
+ this._releaseCanvasCache();
213
317
  this._filterUpToDate = false;
214
318
  if (conf.imageSmoothingEnabled === false) {
215
319
  cachedSceneCanvas.getContext()._context.imageSmoothingEnabled = false;
216
320
  cachedFilterCanvas.getContext()._context.imageSmoothingEnabled = false;
217
321
  }
218
322
  sceneContext.save();
219
- bufferContext.save();
220
323
  sceneContext.translate(-x, -y);
221
- bufferContext.translate(-x, -y);
222
- bufferCanvas.x = x;
223
- bufferCanvas.y = y;
324
+ // extra flag to skip on getAbsolute opacity calc
224
325
  this._isUnderCache = true;
225
326
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
226
- this._clearSelfAndDescendantCache(ABSOLUTE_SCALE);
227
- this.drawScene(cachedSceneCanvas, this, bufferCanvas);
228
- this._isUnderCache = false;
229
- sceneContext.restore();
327
+ try {
328
+ this.drawScene(cachedSceneCanvas, this, bufferCanvas);
329
+ }
330
+ catch (e) {
331
+ Util.releaseCanvas(cachedSceneCanvas._canvas);
332
+ throw e;
333
+ }
334
+ finally {
335
+ this._isUnderCache = false;
336
+ // descendants cached their opacity relative to this node while drawing
337
+ this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
338
+ sceneContext.restore();
339
+ // the buffer is only needed while drawing
340
+ Util.releaseCanvas(bufferCanvas._canvas);
341
+ }
342
+ // this will draw a red border around the cached box for
343
+ // debugging purposes
230
344
  if (drawBorder) {
231
345
  sceneContext.save();
232
346
  sceneContext.beginPath();
@@ -237,10 +351,10 @@ export class Node {
237
351
  sceneContext.stroke();
238
352
  sceneContext.restore();
239
353
  }
240
- Util.releaseCanvas(bufferCanvas._canvas);
241
- this._cache.set(CANVAS, {
354
+ this._canvasCache = {
242
355
  scene: cachedSceneCanvas,
243
356
  filter: cachedFilterCanvas,
357
+ // the hit canvas is built on demand (see _getCachedHitCanvas)
244
358
  hit: null,
245
359
  hitConfig: {
246
360
  pixelRatio: hitCanvasPixelRatio,
@@ -249,11 +363,17 @@ export class Node {
249
363
  },
250
364
  x: x,
251
365
  y: y,
252
- });
366
+ };
253
367
  this._requestDraw();
254
368
  return this;
255
369
  }
370
+ // build the hit canvas of a cached node lazily - only when the hit graph
371
+ // is actually needed, so a non-listening node never allocates it
372
+ // https://github.com/konvajs/konva/issues/2009
256
373
  _getCachedHitCanvas(top) {
374
+ // top === this means the node is drawing into its own cache right now:
375
+ // the build below re-enters drawHit for this very node, and consulting
376
+ // the not-yet-stored canvas again would recurse forever
257
377
  if (top === this) {
258
378
  return null;
259
379
  }
@@ -274,10 +394,54 @@ export class Node {
274
394
  cache.hit = hitCanvas;
275
395
  return hitCanvas;
276
396
  }
397
+ /**
398
+ * determine if node is currently cached
399
+ * @method
400
+ * @name Konva.Node#isCached
401
+ * @returns {Boolean}
402
+ */
277
403
  isCached() {
278
- return this._cache.has(CANVAS);
279
- }
404
+ return !!this._canvasCache;
405
+ }
406
+ /**
407
+ * Return client rectangle {x, y, width, height} of node. This rectangle also include all styling (strokes, shadows, etc).
408
+ * The purpose of the method is similar to getBoundingClientRect API of the DOM.
409
+ * @method
410
+ * @name Konva.Node#getClientRect
411
+ * @param {Object} config
412
+ * @param {Boolean} [config.skipTransform] should we apply transform to node for calculating rect?
413
+ * @param {Boolean} [config.skipShadow] should we apply shadow to the node for calculating bound box?
414
+ * @param {Boolean} [config.skipStroke] should we apply stroke to the node for calculating bound box?
415
+ * @param {Object} [config.relativeTo] calculate client rect relative to one of the parents
416
+ * @returns {Object} rect with {x, y, width, height} properties
417
+ * @example
418
+ * var rect = new Konva.Rect({
419
+ * width : 100,
420
+ * height : 100,
421
+ * x : 50,
422
+ * y : 50,
423
+ * strokeWidth : 4,
424
+ * stroke : 'black',
425
+ * offsetX : 50,
426
+ * scaleY : 2
427
+ * });
428
+ *
429
+ * // get client rect without think off transformations (position, rotation, scale, offset, etc)
430
+ * rect.getClientRect({ skipTransform: true});
431
+ * // returns {
432
+ * // x : -2, // two pixels for stroke / 2
433
+ * // y : -2,
434
+ * // width : 104, // increased by 4 for stroke
435
+ * // height : 104
436
+ * //}
437
+ *
438
+ * // get client rect with transformation applied
439
+ * rect.getClientRect();
440
+ * // returns Object {x: -2, y: 46, width: 104, height: 208}
441
+ */
280
442
  getClientRect(config) {
443
+ // abstract method
444
+ // redefine in Container and Shape
281
445
  throw new Error('abstract "getClientRect" method call');
282
446
  }
283
447
  _transformedRect(rect, top) {
@@ -291,10 +455,6 @@ export class Node {
291
455
  const trans = this.getAbsoluteTransform(top);
292
456
  points.forEach(function (point) {
293
457
  const transformed = trans.point(point);
294
- if (minX === undefined) {
295
- minX = maxX = transformed.x;
296
- minY = maxY = transformed.y;
297
- }
298
458
  minX = Math.min(minX, transformed.x);
299
459
  minY = Math.min(minY, transformed.y);
300
460
  maxX = Math.max(maxX, transformed.x);
@@ -335,18 +495,16 @@ export class Node {
335
495
  }
336
496
  let useNativeOnly = true;
337
497
  for (let i = 0; i < filters.length; i++) {
338
- const fallbackRequired = typeof filters[i] === 'string' && !isCSSFiltersSupported();
339
- if (fallbackRequired) {
340
- }
341
498
  if (typeof filters[i] !== 'string' || !isCSSFiltersSupported()) {
342
499
  useNativeOnly = false;
343
500
  break;
344
501
  }
345
502
  }
346
503
  const ratio = sceneCanvas.pixelRatio;
347
- filterCanvas.setSize(sceneCanvas.width / sceneCanvas.pixelRatio, sceneCanvas.height / sceneCanvas.pixelRatio);
504
+ filterCanvas.setSizeIfChanged(sceneCanvas._logicalWidth, sceneCanvas._logicalHeight);
348
505
  if (useNativeOnly) {
349
506
  const finalFilter = filters.join(' ');
507
+ filterContext.clear();
350
508
  filterContext.save();
351
509
  filterContext.setAttr('filter', finalFilter);
352
510
  filterContext.drawImage(sceneCanvas._canvas, 0, 0, sceneCanvas.getWidth() / ratio, sceneCanvas.getHeight() / ratio);
@@ -357,16 +515,18 @@ export class Node {
357
515
  try {
358
516
  len = filters.length;
359
517
  filterContext.clear();
518
+ // copy cached canvas onto filter context
360
519
  filterContext.drawImage(sceneCanvas._canvas, 0, 0, sceneCanvas.getWidth() / ratio, sceneCanvas.getHeight() / ratio);
361
520
  imageData = filterContext.getImageData(0, 0, filterCanvas.getWidth(), filterCanvas.getHeight());
521
+ // apply filters to filter context
362
522
  for (n = 0; n < len; n++) {
363
523
  filter = filters[n];
364
524
  if (typeof filter === 'string') {
365
525
  filter = parseCSSFilters(filter);
366
526
  }
367
527
  filter.call(this, imageData);
368
- filterContext.putImageData(imageData, 0, 0);
369
528
  }
529
+ filterContext.putImageData(imageData, 0, 0);
370
530
  }
371
531
  catch (e) {
372
532
  Util.error('Unable to apply filter. ' +
@@ -376,22 +536,87 @@ export class Node {
376
536
  this._filterUpToDate = true;
377
537
  return filterCanvas;
378
538
  }
539
+ /**
540
+ * bind events to the node. KonvaJS supports mouseover, mousemove,
541
+ * mouseout, mouseenter, mouseleave, mousedown, mouseup, wheel, contextmenu, click, dblclick, touchstart, touchmove,
542
+ * touchend, tap, dbltap, dragstart, dragmove, dragend and destroy events.
543
+ * Pass in a string of events delimited by a space to bind multiple events at once
544
+ * such as 'mousedown mouseup mousemove'. Include a namespace to bind an
545
+ * event by name such as 'click.foobar'.
546
+ * @method
547
+ * @name Konva.Node#on
548
+ * @param {String} evtStr e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo'
549
+ * @param {Function} handler The handler function. The first argument of that function is event object. Event object has `target` as main target of the event, `currentTarget` as current node listener and `evt` as native browser event.
550
+ * @returns {Konva.Node}
551
+ * @example
552
+ * // add click listener
553
+ * node.on('click', function() {
554
+ * console.log('you clicked me!');
555
+ * });
556
+ *
557
+ * // get the target node
558
+ * node.on('click', function(evt) {
559
+ * console.log(evt.target);
560
+ * });
561
+ *
562
+ * // stop event propagation
563
+ * node.on('click', function(evt) {
564
+ * evt.cancelBubble = true;
565
+ * });
566
+ *
567
+ * // bind multiple listeners
568
+ * node.on('click touchstart', function() {
569
+ * console.log('you clicked/touched me!');
570
+ * });
571
+ *
572
+ * // namespace listener
573
+ * node.on('click.foo', function() {
574
+ * console.log('you clicked/touched me!');
575
+ * });
576
+ *
577
+ * // get the event type
578
+ * node.on('click tap', function(evt) {
579
+ * var eventType = evt.type;
580
+ * });
581
+ *
582
+ * // get native event object
583
+ * node.on('click tap', function(evt) {
584
+ * var nativeEvent = evt.evt;
585
+ * });
586
+ *
587
+ * // for change events, get the old and new val
588
+ * node.on('xChange', function(evt) {
589
+ * var oldVal = evt.oldVal;
590
+ * var newVal = evt.newVal;
591
+ * });
592
+ *
593
+ * // get event targets
594
+ * // with event delegations
595
+ * layer.on('click', 'Group', function(evt) {
596
+ * var shape = evt.target;
597
+ * var group = evt.currentTarget;
598
+ * });
599
+ */
379
600
  on(...args) {
601
+ this._prepareListeners();
380
602
  const evtStr = args[0];
381
603
  const selectorOrHandler = args[1];
382
604
  const handler = args[2];
383
- if (this._cache) {
384
- this._cache.delete(ALL_LISTENERS);
385
- }
386
605
  if (args.length === 3) {
387
606
  return this._delegate.apply(this, args);
388
607
  }
389
608
  const events = evtStr.split(SPACE);
609
+ /*
610
+ * loop through types and attach event listeners to
611
+ * each one. eg. 'click mouseover.namespace mouseout'
612
+ * will create three event bindings
613
+ */
390
614
  for (let n = 0; n < events.length; n++) {
391
615
  const event = events[n];
392
616
  const parts = event.split('.');
393
617
  const baseEvent = parts[0];
394
618
  const name = parts[1] || '';
619
+ // create events array if it doesn't exist
395
620
  if (!this.eventListeners[baseEvent]) {
396
621
  this.eventListeners[baseEvent] = [];
397
622
  }
@@ -399,10 +624,42 @@ export class Node {
399
624
  }
400
625
  return this;
401
626
  }
627
+ /**
628
+ * remove event bindings from the node. Pass in a string of
629
+ * event types delimmited by a space to remove multiple event
630
+ * bindings at once such as 'mousedown mouseup mousemove'.
631
+ * include a namespace to remove an event binding by name
632
+ * such as 'click.foobar'. If you only give a name like '.foobar',
633
+ * all events in that namespace will be removed.
634
+ * @method
635
+ * @name Konva.Node#off
636
+ * @param {String} evtStr e.g. 'click', 'mousedown touchstart', '.foobar'
637
+ * @returns {Konva.Node}
638
+ * @example
639
+ * // remove listener
640
+ * node.off('click');
641
+ *
642
+ * // remove multiple listeners
643
+ * node.off('click touchstart');
644
+ *
645
+ * // remove listener by name
646
+ * node.off('click.foo');
647
+ */
648
+ // listeners added to a prototype go into its own map, not the parent's,
649
+ // and the lists flattened from the prototype chain so far are stale
650
+ _prepareListeners() {
651
+ if (this === this.constructor.prototype) {
652
+ if (!this.hasOwnProperty('eventListeners')) {
653
+ this.eventListeners = {};
654
+ }
655
+ Node.protoListenerMap = new WeakMap();
656
+ }
657
+ }
402
658
  off(evtStr, callback) {
659
+ this._prepareListeners();
403
660
  let events = (evtStr || '').split(SPACE), len = events.length, n, t, event, parts, baseEvent, name;
404
- this._cache && this._cache.delete(ALL_LISTENERS);
405
661
  if (!evtStr) {
662
+ // remove all events
406
663
  for (t in this.eventListeners) {
407
664
  this._off(t);
408
665
  }
@@ -425,6 +682,7 @@ export class Node {
425
682
  }
426
683
  return this;
427
684
  }
685
+ // some event aliases for third party integration like HammerJS
428
686
  dispatchEvent(evt) {
429
687
  const e = {
430
688
  target: this,
@@ -435,6 +693,7 @@ export class Node {
435
693
  return this;
436
694
  }
437
695
  addEventListener(type, handler) {
696
+ // we have to pass native event to handler
438
697
  this.on(type, function (evt) {
439
698
  handler.call(this, evt.evt);
440
699
  });
@@ -444,6 +703,7 @@ export class Node {
444
703
  this.off(type);
445
704
  return this;
446
705
  }
706
+ // like node.on
447
707
  _delegate(event, selector, handler) {
448
708
  const stopNode = this;
449
709
  this.on(event, function (evt) {
@@ -456,11 +716,23 @@ export class Node {
456
716
  });
457
717
  return this;
458
718
  }
719
+ /**
720
+ * remove a node from parent, but don't destroy. You can reuse the node later.
721
+ * @method
722
+ * @name Konva.Node#remove
723
+ * @returns {Konva.Node}
724
+ * @example
725
+ * node.remove();
726
+ */
459
727
  remove() {
460
728
  if (this.isDragging()) {
461
729
  this.stopDrag();
462
730
  }
731
+ // we can have drag element but that is not dragged yet
732
+ // so just clear it
463
733
  DD._dragElements.delete(this._id);
734
+ // also remove any dragging descendants, otherwise they'll
735
+ // have a broken parent chain and crash on getStage()
464
736
  DD._dragElements.forEach((elem, key) => {
465
737
  if (this.isAncestorOf(elem.node)) {
466
738
  DD._dragElements.delete(key);
@@ -472,12 +744,13 @@ export class Node {
472
744
  _clearCaches() {
473
745
  this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
474
746
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
475
- this._clearSelfAndDescendantCache(ABSOLUTE_SCALE);
476
747
  this._clearSelfAndDescendantCache(STAGE);
477
748
  this._clearSelfAndDescendantCache(VISIBLE);
478
749
  this._clearSelfAndDescendantCache(LISTENING);
479
750
  }
480
751
  _remove() {
752
+ // every cached attr that is calculated via node tree
753
+ // traversal must be cleared when removing a node
481
754
  this._clearCaches();
482
755
  const parent = this.getParent();
483
756
  if (parent && parent.children) {
@@ -486,18 +759,51 @@ export class Node {
486
759
  this.parent = null;
487
760
  }
488
761
  }
762
+ /**
763
+ * remove and destroy a node. Kill it and delete forever! You should not reuse node after destroy().
764
+ * If the node is a container (Group, Stage or Layer) it will destroy all children too.
765
+ * The node fires a `destroy` event first, so anything holding a reference to it can let go.
766
+ * When an ancestor is being destroyed the node is already detached from its parent at that point.
767
+ * @method
768
+ * @name Konva.Node#destroy
769
+ * @example
770
+ * node.on('destroy', () => console.log('gone'));
771
+ * node.destroy();
772
+ */
489
773
  destroy() {
774
+ this._fire('destroy', { target: this });
775
+ PointerEvents.releaseCapturesOf(this);
490
776
  this.remove();
491
777
  this.clearCache();
492
778
  return this;
493
779
  }
780
+ /**
781
+ * get attr
782
+ * @method
783
+ * @name Konva.Node#getAttr
784
+ * @param {String} attr
785
+ * @returns {Integer|String|Object|Array}
786
+ * @example
787
+ * var x = node.getAttr('x');
788
+ */
494
789
  getAttr(attr) {
495
790
  const method = 'get' + Util._capitalize(attr);
496
791
  if (Util._isFunction(this[method])) {
497
792
  return this[method]();
498
793
  }
794
+ // otherwise get directly
499
795
  return this.attrs[attr];
500
796
  }
797
+ /**
798
+ * get ancestors
799
+ * @method
800
+ * @name Konva.Node#getAncestors
801
+ * @returns {Array}
802
+ * @example
803
+ * shape.getAncestors().forEach(function(node) {
804
+ * console.log(node.id());
805
+ * })
806
+ */
501
807
  getAncestors() {
502
808
  let parent = this.getParent(), ancestors = [];
503
809
  while (parent) {
@@ -506,9 +812,27 @@ export class Node {
506
812
  }
507
813
  return ancestors;
508
814
  }
815
+ /**
816
+ * get attrs object literal
817
+ * @method
818
+ * @name Konva.Node#getAttrs
819
+ * @returns {Object}
820
+ */
509
821
  getAttrs() {
510
822
  return this.attrs || {};
511
823
  }
824
+ /**
825
+ * set multiple attrs at once using an object literal
826
+ * @method
827
+ * @name Konva.Node#setAttrs
828
+ * @param {Object} config object containing key value pairs
829
+ * @returns {Konva.Node}
830
+ * @example
831
+ * node.setAttrs({
832
+ * x: 5,
833
+ * fill: 'red'
834
+ * });
835
+ */
512
836
  setAttrs(config) {
513
837
  this._batchTransformChanges(() => {
514
838
  let key, method;
@@ -520,16 +844,33 @@ export class Node {
520
844
  continue;
521
845
  }
522
846
  method = SET + Util._capitalize(key);
847
+ // use setter if available
523
848
  if (Util._isFunction(this[method])) {
524
849
  this[method](config[key]);
525
850
  }
526
851
  else {
852
+ // otherwise set directly
527
853
  this._setAttr(key, config[key]);
528
854
  }
529
855
  }
530
856
  });
531
857
  return this;
532
858
  }
859
+ /**
860
+ * determine if node is listening for events by taking into account ancestors.
861
+ *
862
+ * Parent | Self | isListening
863
+ * listening | listening |
864
+ * ----------+-----------+------------
865
+ * T | T | T
866
+ * T | F | F
867
+ * F | T | F
868
+ * F | F | F
869
+ *
870
+ * @method
871
+ * @name Konva.Node#isListening
872
+ * @returns {Boolean}
873
+ */
533
874
  isListening() {
534
875
  return this._getCache(LISTENING, this._isListening);
535
876
  }
@@ -546,6 +887,20 @@ export class Node {
546
887
  return true;
547
888
  }
548
889
  }
890
+ /**
891
+ * determine if node is visible by taking into account ancestors.
892
+ *
893
+ * Parent | Self | isVisible
894
+ * visible | visible |
895
+ * ----------+-----------+------------
896
+ * T | T | T
897
+ * T | F | F
898
+ * F | T | F
899
+ * F | F | F
900
+ * @method
901
+ * @name Konva.Node#isVisible
902
+ * @returns {Boolean}
903
+ */
549
904
  isVisible() {
550
905
  return this._getCache(VISIBLE, this._isVisible);
551
906
  }
@@ -562,32 +917,28 @@ export class Node {
562
917
  return true;
563
918
  }
564
919
  }
565
- shouldDrawHit(top, skipDragCheck = false) {
920
+ shouldDrawHit(top) {
566
921
  if (top) {
567
922
  return this._isVisible(top) && this._isListening(top);
568
923
  }
569
- const layer = this.getLayer();
570
- let layerUnderDrag = false;
571
- DD._dragElements.forEach((elem) => {
572
- if (elem.dragStatus !== 'dragging') {
573
- return;
574
- }
575
- else if (elem.node.nodeType === 'Stage') {
576
- layerUnderDrag = true;
577
- }
578
- else if (elem.node.getLayer() === layer) {
579
- layerUnderDrag = true;
580
- }
581
- });
582
- const dragSkip = !skipDragCheck &&
583
- !Konva.hitOnDragEnabled &&
584
- (layerUnderDrag || Konva.isTransforming());
585
- return this.isListening() && this.isVisible() && !dragSkip;
924
+ return this.isListening() && this.isVisible();
586
925
  }
926
+ /**
927
+ * show node. set visible = true
928
+ * @method
929
+ * @name Konva.Node#show
930
+ * @returns {Konva.Node}
931
+ */
587
932
  show() {
588
933
  this.visible(true);
589
934
  return this;
590
935
  }
936
+ /**
937
+ * hide node. Hidden nodes are no longer detectable
938
+ * @method
939
+ * @name Konva.Node#hide
940
+ * @returns {Konva.Node}
941
+ */
591
942
  hide() {
592
943
  this.visible(false);
593
944
  return this;
@@ -595,6 +946,13 @@ export class Node {
595
946
  getZIndex() {
596
947
  return this.index || 0;
597
948
  }
949
+ /**
950
+ * get absolute z-index which takes into account sibling
951
+ * and ancestor indices
952
+ * @method
953
+ * @name Konva.Node#getAbsoluteZIndex
954
+ * @returns {Integer}
955
+ */
598
956
  getAbsoluteZIndex() {
599
957
  let depth = this.getDepth(), that = this, index = 0, nodes, len, n, child;
600
958
  function addChildren(children) {
@@ -604,7 +962,7 @@ export class Node {
604
962
  child = children[n];
605
963
  index++;
606
964
  if (child.nodeType !== SHAPE) {
607
- nodes = nodes.concat(child.getChildren().slice());
965
+ nodes = nodes.concat(child.children);
608
966
  }
609
967
  if (child._id === that._id) {
610
968
  n = len;
@@ -616,10 +974,20 @@ export class Node {
616
974
  }
617
975
  const stage = this.getStage();
618
976
  if (that.nodeType !== UPPER_STAGE && stage) {
619
- addChildren(stage.getChildren());
977
+ addChildren(stage.children);
620
978
  }
621
979
  return index;
622
980
  }
981
+ /**
982
+ * get node depth in node tree. Returns an integer.
983
+ * e.g. Stage depth will always be 0. Layers will always be 1. Groups and Shapes will always
984
+ * be >= 2
985
+ * @method
986
+ * @name Konva.Node#getDepth
987
+ * @returns {Integer}
988
+ * @example
989
+ * var depth = shape.getDepth(); // 2 for a shape right inside of a layer
990
+ */
623
991
  getDepth() {
624
992
  let depth = 0, parent = this.parent;
625
993
  while (parent) {
@@ -628,15 +996,23 @@ export class Node {
628
996
  }
629
997
  return depth;
630
998
  }
999
+ // sometimes we do several attributes changes
1000
+ // like node.position(pos)
1001
+ // for performance reasons, lets batch transform reset
1002
+ // so it work faster
631
1003
  _batchTransformChanges(func) {
632
1004
  this._batchingTransformChange = true;
633
- func();
634
- this._batchingTransformChange = false;
635
- if (this._needClearTransformCache) {
636
- this._clearCache(TRANSFORM);
637
- this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
1005
+ try {
1006
+ func();
1007
+ }
1008
+ finally {
1009
+ this._batchingTransformChange = false;
1010
+ if (this._needClearTransformCache) {
1011
+ this._needClearTransformCache = false;
1012
+ this._clearCache(TRANSFORM);
1013
+ this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
1014
+ }
638
1015
  }
639
- this._needClearTransformCache = false;
640
1016
  }
641
1017
  setPosition(pos) {
642
1018
  this._batchTransformChanges(() => {
@@ -651,51 +1027,75 @@ export class Node {
651
1027
  y: this.y(),
652
1028
  };
653
1029
  }
1030
+ /**
1031
+ * get position of first pointer (like mouse or first touch) relative to local coordinates of current node
1032
+ * @method
1033
+ * @name Konva.Node#getRelativePointerPosition
1034
+ * @returns {Konva.Node}
1035
+ * @example
1036
+ *
1037
+ * // let's think we have a rectangle at position x = 10, y = 10
1038
+ * // now we clicked at x = 15, y = 15 of the stage
1039
+ * // if you want to know position of the click, related to the rectangle you can use
1040
+ * rect.getRelativePointerPosition();
1041
+ */
654
1042
  getRelativePointerPosition() {
655
1043
  const stage = this.getStage();
656
1044
  if (!stage) {
657
1045
  return null;
658
1046
  }
1047
+ // get pointer (say mouse or touch) position
659
1048
  const pos = stage.getPointerPosition();
660
1049
  if (!pos) {
661
1050
  return null;
662
1051
  }
663
1052
  const transform = this.getAbsoluteTransform().copy();
1053
+ // to detect relative position we need to invert transform
664
1054
  transform.invert();
1055
+ // now we can find relative point
665
1056
  return transform.point(pos);
666
1057
  }
1058
+ /**
1059
+ * get absolute position of a node. That function can be used to calculate absolute position, but relative to any ancestor
1060
+ * @method
1061
+ * @name Konva.Node#getAbsolutePosition
1062
+ * @param {Object} [top] optional ancestor node
1063
+ * @returns {Konva.Node}
1064
+ * @example
1065
+ *
1066
+ * // returns absolute position relative to top-left corner of canvas
1067
+ * node.getAbsolutePosition();
1068
+ *
1069
+ * // calculate absolute position of node, inside stage
1070
+ * // so stage transforms are ignored
1071
+ * node.getAbsolutePosition(stage)
1072
+ */
667
1073
  getAbsolutePosition(top) {
668
- let haveCachedParent = false;
669
- let parent = this.parent;
670
- while (parent) {
671
- if (parent.isCached()) {
672
- haveCachedParent = true;
673
- break;
674
- }
675
- parent = parent.parent;
676
- }
677
- if (haveCachedParent && !top) {
678
- top = true;
679
- }
680
1074
  const absoluteMatrix = this.getAbsoluteTransform(top).getMatrix(), absoluteTransform = new Transform(), offset = this.offset();
1075
+ // clone the matrix array
681
1076
  absoluteTransform.m = absoluteMatrix.slice();
682
1077
  absoluteTransform.translate(offset.x, offset.y);
683
1078
  return absoluteTransform.getTranslation();
684
1079
  }
685
1080
  setAbsolutePosition(pos) {
686
1081
  const { x, y, ...origTrans } = this._clearTransform();
1082
+ // don't clear translation
687
1083
  this.attrs.x = x;
688
1084
  this.attrs.y = y;
1085
+ // important, use non cached value
689
1086
  this._clearCache(TRANSFORM);
690
1087
  const it = this._getAbsoluteTransform().copy();
1088
+ const invertible = it.isInvertible();
691
1089
  it.invert();
692
1090
  it.translate(pos.x, pos.y);
693
- pos = {
694
- x: this.attrs.x + it.getTranslation().x,
695
- y: this.attrs.y + it.getTranslation().y,
696
- };
1091
+ const { x: dx, y: dy } = it.getTranslation();
697
1092
  this._setTransform(origTrans);
698
- this.setPosition({ x: pos.x, y: pos.y });
1093
+ if (invertible) {
1094
+ this.setPosition({ x: this.attrs.x + dx, y: this.attrs.y + dy });
1095
+ }
1096
+ else {
1097
+ Util.warn('Cannot set the absolute position: the absolute transform is not invertible (an ancestor has a zero scale).');
1098
+ }
699
1099
  this._clearCache(TRANSFORM);
700
1100
  this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM);
701
1101
  return this;
@@ -727,8 +1127,24 @@ export class Node {
727
1127
  this.attrs.offsetY = 0;
728
1128
  this.attrs.skewX = 0;
729
1129
  this.attrs.skewY = 0;
1130
+ // return original transform
730
1131
  return trans;
731
1132
  }
1133
+ /**
1134
+ * move node by an amount relative to its current position
1135
+ * @method
1136
+ * @name Konva.Node#move
1137
+ * @param {Object} change
1138
+ * @param {Number} change.x
1139
+ * @param {Number} change.y
1140
+ * @returns {Konva.Node}
1141
+ * @example
1142
+ * // move node in x direction by 1px and y direction by 2px
1143
+ * node.move({
1144
+ * x: 1,
1145
+ * y: 2
1146
+ * });
1147
+ */
732
1148
  move(change) {
733
1149
  let changeX = change.x, changeY = change.y, x = this.x(), y = this.y();
734
1150
  if (changeX !== undefined) {
@@ -740,31 +1156,29 @@ export class Node {
740
1156
  this.setPosition({ x: x, y: y });
741
1157
  return this;
742
1158
  }
743
- _eachAncestorReverse(func, top) {
744
- let family = [], parent = this.getParent(), len, n;
745
- if (top && top._id === this._id) {
746
- return;
747
- }
748
- family.unshift(this);
749
- while (parent && (!top || parent._id !== top._id)) {
750
- family.unshift(parent);
751
- parent = parent.parent;
752
- }
753
- len = family.length;
754
- for (n = 0; n < len; n++) {
755
- func(family[n]);
756
- }
757
- }
1159
+ /**
1160
+ * rotate node by an amount in degrees relative to its current rotation
1161
+ * @method
1162
+ * @name Konva.Node#rotate
1163
+ * @param {Number} theta
1164
+ * @returns {Konva.Node}
1165
+ */
758
1166
  rotate(theta) {
759
1167
  this.rotation(this.rotation() + theta);
760
1168
  return this;
761
1169
  }
1170
+ /**
1171
+ * move node to the top of its siblings
1172
+ * @method
1173
+ * @name Konva.Node#moveToTop
1174
+ * @returns {Boolean}
1175
+ */
762
1176
  moveToTop() {
763
1177
  if (!this.parent) {
764
1178
  Util.warn('Node has no parent. moveToTop function is ignored.');
765
1179
  return false;
766
1180
  }
767
- const index = this.index, len = this.parent.getChildren().length;
1181
+ const index = this.index, len = this.parent.children.length;
768
1182
  if (index < len - 1) {
769
1183
  this.parent.children.splice(index, 1);
770
1184
  this.parent.children.push(this);
@@ -773,12 +1187,18 @@ export class Node {
773
1187
  }
774
1188
  return false;
775
1189
  }
1190
+ /**
1191
+ * move node up
1192
+ * @method
1193
+ * @name Konva.Node#moveUp
1194
+ * @returns {Boolean} flag is moved or not
1195
+ */
776
1196
  moveUp() {
777
1197
  if (!this.parent) {
778
1198
  Util.warn('Node has no parent. moveUp function is ignored.');
779
1199
  return false;
780
1200
  }
781
- const index = this.index, len = this.parent.getChildren().length;
1201
+ const index = this.index, len = this.parent.children.length;
782
1202
  if (index < len - 1) {
783
1203
  this.parent.children.splice(index, 1);
784
1204
  this.parent.children.splice(index + 1, 0, this);
@@ -787,6 +1207,12 @@ export class Node {
787
1207
  }
788
1208
  return false;
789
1209
  }
1210
+ /**
1211
+ * move node down
1212
+ * @method
1213
+ * @name Konva.Node#moveDown
1214
+ * @returns {Boolean}
1215
+ */
790
1216
  moveDown() {
791
1217
  if (!this.parent) {
792
1218
  Util.warn('Node has no parent. moveDown function is ignored.');
@@ -801,6 +1227,12 @@ export class Node {
801
1227
  }
802
1228
  return false;
803
1229
  }
1230
+ /**
1231
+ * move node to the bottom of its siblings
1232
+ * @method
1233
+ * @name Konva.Node#moveToBottom
1234
+ * @returns {Boolean}
1235
+ */
804
1236
  moveToBottom() {
805
1237
  if (!this.parent) {
806
1238
  Util.warn('Node has no parent. moveToBottom function is ignored.');
@@ -833,6 +1265,12 @@ export class Node {
833
1265
  this.parent._setChildrenIndices();
834
1266
  return this;
835
1267
  }
1268
+ /**
1269
+ * get absolute opacity
1270
+ * @method
1271
+ * @name Konva.Node#getAbsoluteOpacity
1272
+ * @returns {Number}
1273
+ */
836
1274
  getAbsoluteOpacity() {
837
1275
  return this._getCache(ABSOLUTE_OPACITY, this._getAbsoluteOpacity);
838
1276
  }
@@ -844,14 +1282,32 @@ export class Node {
844
1282
  }
845
1283
  return absOpacity;
846
1284
  }
1285
+ /**
1286
+ * move node to another container
1287
+ * @method
1288
+ * @name Konva.Node#moveTo
1289
+ * @param {Container} newContainer
1290
+ * @returns {Konva.Node}
1291
+ * @example
1292
+ * // move node from current layer into layer2
1293
+ * node.moveTo(layer2);
1294
+ */
847
1295
  moveTo(newContainer) {
1296
+ // do nothing if new container is already parent
848
1297
  if (this.getParent() !== newContainer) {
849
1298
  this._remove();
850
1299
  newContainer.add(this);
851
1300
  }
852
1301
  return this;
853
1302
  }
1303
+ /**
1304
+ * convert Node into an object for serialization. Returns an object.
1305
+ * @method
1306
+ * @name Konva.Node#toObject
1307
+ * @returns {Object}
1308
+ */
854
1309
  toObject() {
1310
+ var _a;
855
1311
  let attrs = this.getAttrs(), key, val, getter, defaultValue, nonPlainObject;
856
1312
  const obj = {
857
1313
  attrs: {},
@@ -859,27 +1315,59 @@ export class Node {
859
1315
  };
860
1316
  for (key in attrs) {
861
1317
  val = attrs[key];
1318
+ // if value is object and object is not plain
1319
+ // like class instance, we should skip it and to not include
862
1320
  nonPlainObject =
863
1321
  Util.isObject(val) && !Util._isPlainObject(val) && !Util._isArray(val);
864
1322
  if (nonPlainObject) {
865
1323
  continue;
866
1324
  }
867
- getter = typeof this[key] === 'function' && this[key];
1325
+ // a custom attribute may share its name with a node method, so only
1326
+ // the accessors generated by Factory are asked for the default value
1327
+ getter = ((_a = this[key]) === null || _a === void 0 ? void 0 : _a._isAttrAccessor) && this[key];
1328
+ // remove attr value so that we can extract the default value from the getter
868
1329
  delete attrs[key];
869
1330
  defaultValue = getter ? getter.call(this) : null;
1331
+ // restore attr value
870
1332
  attrs[key] = val;
871
1333
  if (defaultValue !== val) {
872
- obj.attrs[key] = val;
1334
+ obj.attrs[key] = Util.isObject(val)
1335
+ ? Util._prepareToStringify(val)
1336
+ : val;
873
1337
  }
874
1338
  }
875
- return Util._prepareToStringify(obj);
1339
+ return obj;
876
1340
  }
1341
+ /**
1342
+ * convert Node into a JSON string. Returns a JSON string.
1343
+ * @method
1344
+ * @name Konva.Node#toJSON
1345
+ * @returns {String}
1346
+ */
877
1347
  toJSON() {
878
1348
  return JSON.stringify(this.toObject());
879
1349
  }
1350
+ /**
1351
+ * get parent container
1352
+ * @method
1353
+ * @name Konva.Node#getParent
1354
+ * @returns {Konva.Node}
1355
+ */
880
1356
  getParent() {
881
1357
  return this.parent;
882
1358
  }
1359
+ /**
1360
+ * get all ancestors (parent then parent of the parent, etc) of the node
1361
+ * @method
1362
+ * @name Konva.Node#findAncestors
1363
+ * @param {String} selector selector for search
1364
+ * @param {Boolean} [includeSelf] show we think that node is ancestro itself?
1365
+ * @param {Konva.Node} [stopNode] optional node where we need to stop searching (one of ancestors)
1366
+ * @returns {Array} [ancestors]
1367
+ * @example
1368
+ * // get one of the parent group
1369
+ * var parentGroups = node.findAncestors('Group');
1370
+ */
883
1371
  findAncestors(selector, includeSelf, stopNode) {
884
1372
  const res = [];
885
1373
  if (includeSelf && this._isMatch(selector)) {
@@ -900,9 +1388,22 @@ export class Node {
900
1388
  isAncestorOf(node) {
901
1389
  return false;
902
1390
  }
1391
+ /**
1392
+ * get ancestor (parent or parent of the parent, etc) of the node that match passed selector
1393
+ * @method
1394
+ * @name Konva.Node#findAncestor
1395
+ * @param {String} selector selector for search
1396
+ * @param {Boolean} [includeSelf] show we think that node is ancestro itself?
1397
+ * @param {Konva.Node} [stopNode] optional node where we need to stop searching (one of ancestors)
1398
+ * @returns {Konva.Node} ancestor
1399
+ * @example
1400
+ * // get one of the parent group
1401
+ * var group = node.findAncestors('.mygroup');
1402
+ */
903
1403
  findAncestor(selector, includeSelf, stopNode) {
904
1404
  return this.findAncestors(selector, includeSelf, stopNode)[0];
905
1405
  }
1406
+ // is current node match passed selector?
906
1407
  _isMatch(selector) {
907
1408
  if (!selector) {
908
1409
  return false;
@@ -920,12 +1421,14 @@ export class Node {
920
1421
  Util.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".');
921
1422
  Util.warn('Konva is awesome, right?');
922
1423
  }
1424
+ // id selector
923
1425
  if (sel.charAt(0) === '#') {
924
1426
  if (this.id() === sel.slice(1)) {
925
1427
  return true;
926
1428
  }
927
1429
  }
928
1430
  else if (sel.charAt(0) === '.') {
1431
+ // name selector
929
1432
  if (this.hasName(sel.slice(1))) {
930
1433
  return true;
931
1434
  }
@@ -936,10 +1439,22 @@ export class Node {
936
1439
  }
937
1440
  return false;
938
1441
  }
1442
+ /**
1443
+ * get layer ancestor
1444
+ * @method
1445
+ * @name Konva.Node#getLayer
1446
+ * @returns {Konva.Layer}
1447
+ */
939
1448
  getLayer() {
940
1449
  const parent = this.getParent();
941
1450
  return parent ? parent.getLayer() : null;
942
1451
  }
1452
+ /**
1453
+ * get stage ancestor
1454
+ * @method
1455
+ * @name Konva.Node#getStage
1456
+ * @returns {Konva.Stage}
1457
+ */
943
1458
  getStage() {
944
1459
  return this._getCache(STAGE, this._getStage);
945
1460
  }
@@ -952,63 +1467,124 @@ export class Node {
952
1467
  return null;
953
1468
  }
954
1469
  }
955
- fire(eventType, evt = {}, bubble) {
1470
+ /**
1471
+ * fire event
1472
+ * @method
1473
+ * @name Konva.Node#fire
1474
+ * @param {String} eventType event type. can be a regular event, like click, mouseover, or mouseout, or it can be a custom event, like myCustomEvent
1475
+ * @param {Event} [evt] event object
1476
+ * @param {Boolean} [bubble] setting the value to false, or leaving it undefined, will result in the event
1477
+ * not bubbling. Setting the value to true will result in the event bubbling.
1478
+ * @returns {Konva.Node}
1479
+ * @example
1480
+ * // manually fire click event
1481
+ * node.fire('click');
1482
+ *
1483
+ * // fire custom event
1484
+ * node.fire('foo');
1485
+ *
1486
+ * // fire custom event with custom event object
1487
+ * node.fire('foo', {
1488
+ * bar: 10
1489
+ * });
1490
+ *
1491
+ * // fire click event that bubbles
1492
+ * node.fire('click', null, true);
1493
+ */
1494
+ fire(eventType, evt, bubble) {
1495
+ evt = evt || {};
956
1496
  evt.target = evt.target || this;
1497
+ // bubble
957
1498
  if (bubble) {
958
1499
  this._fireAndBubble(eventType, evt);
959
1500
  }
960
1501
  else {
1502
+ // no bubble
961
1503
  this._fire(eventType, evt);
962
1504
  }
963
1505
  return this;
964
1506
  }
1507
+ /**
1508
+ * get absolute transform of the node which takes into
1509
+ * account its ancestor transforms
1510
+ * @method
1511
+ * @name Konva.Node#getAbsoluteTransform
1512
+ * @returns {Konva.Transform}
1513
+ */
965
1514
  getAbsoluteTransform(top) {
966
- if (top) {
1515
+ // relative to an ancestor, or under a cached one, the result can't come
1516
+ // from the cache: a cached container keeps the transform caches of its
1517
+ // descendants while it moves (see Container._clearSelfAndDescendantCache)
1518
+ if (top || this._hasCachedAncestor()) {
967
1519
  return this._getAbsoluteTransform(top);
968
1520
  }
969
- else {
970
- return this._getCache(ABSOLUTE_TRANSFORM, this._getAbsoluteTransform);
1521
+ return this._getCache(ABSOLUTE_TRANSFORM, this._getCachedAbsoluteTransform);
1522
+ }
1523
+ _hasCachedAncestor() {
1524
+ let parent = this.parent;
1525
+ while (parent) {
1526
+ if (parent.isCached()) {
1527
+ return true;
1528
+ }
1529
+ parent = parent.parent;
971
1530
  }
1531
+ return false;
972
1532
  }
1533
+ // relative to `top`: the transforms of `top` and of its ancestors are
1534
+ // left out. Goes through the parent, so an ancestor that redefines its
1535
+ // absolute transform (Konva.Transformer) is honoured
973
1536
  _getAbsoluteTransform(top) {
974
- let at;
975
- if (top) {
976
- at = new Transform();
977
- this._eachAncestorReverse(function (node) {
978
- const transformsEnabled = node.transformsEnabled();
979
- if (transformsEnabled === 'all') {
980
- at.multiply(node.getTransform());
981
- }
982
- else if (transformsEnabled === 'position') {
983
- at.translate(node.x() - node.offsetX(), node.y() - node.offsetY());
984
- }
985
- }, top);
1537
+ const at = new Transform();
1538
+ if (this === top) {
986
1539
  return at;
987
1540
  }
988
- else {
989
- at = this._cache.get(ABSOLUTE_TRANSFORM) || new Transform();
990
- if (this.parent) {
991
- this.parent.getAbsoluteTransform().copyInto(at);
992
- }
993
- else {
994
- at.reset();
995
- }
996
- const transformsEnabled = this.transformsEnabled();
997
- if (transformsEnabled === 'all') {
998
- at.multiply(this.getTransform());
999
- }
1000
- else if (transformsEnabled === 'position') {
1001
- const x = this.attrs.x || 0;
1002
- const y = this.attrs.y || 0;
1003
- const offsetX = this.attrs.offsetX || 0;
1004
- const offsetY = this.attrs.offsetY || 0;
1005
- at.translate(x - offsetX, y - offsetY);
1006
- }
1007
- at.dirty = false;
1008
- return at;
1541
+ if (this.parent && this.parent !== top) {
1542
+ this.parent.getAbsoluteTransform(top).copyInto(at);
1009
1543
  }
1544
+ return this._multiplyOwnTransform(at);
1010
1545
  }
1546
+ // the cached transform of the parent, then the own one
1547
+ _getCachedAbsoluteTransform() {
1548
+ const at = this._cache[ABSOLUTE_TRANSFORM] || new Transform();
1549
+ if (this.parent) {
1550
+ this.parent.getAbsoluteTransform().copyInto(at);
1551
+ }
1552
+ else {
1553
+ at.reset();
1554
+ }
1555
+ this._multiplyOwnTransform(at);
1556
+ at.dirty = false;
1557
+ return at;
1558
+ }
1559
+ _multiplyOwnTransform(at) {
1560
+ const transformsEnabled = this.transformsEnabled();
1561
+ if (transformsEnabled === 'all') {
1562
+ at.multiply(this.getTransform());
1563
+ }
1564
+ else if (transformsEnabled === 'position') {
1565
+ // use "attrs" directly, because it is a bit faster
1566
+ const x = this.attrs.x || 0;
1567
+ const y = this.attrs.y || 0;
1568
+ const offsetX = this.attrs.offsetX || 0;
1569
+ const offsetY = this.attrs.offsetY || 0;
1570
+ at.translate(x - offsetX, y - offsetY);
1571
+ }
1572
+ return at;
1573
+ }
1574
+ /**
1575
+ * get absolute scale of the node which takes into
1576
+ * account its ancestor scales
1577
+ * @method
1578
+ * @name Konva.Node#getAbsoluteScale
1579
+ * @returns {Object}
1580
+ * @example
1581
+ * // get absolute scale x
1582
+ * var scaleX = node.getAbsoluteScale().x;
1583
+ */
1011
1584
  getAbsoluteScale(top) {
1585
+ // do not cache this calculations,
1586
+ // because it use cache transform
1587
+ // this is special logic for caching with some shapes with shadow
1012
1588
  let parent = this;
1013
1589
  while (parent) {
1014
1590
  if (parent._isUnderCache) {
@@ -1023,16 +1599,35 @@ export class Node {
1023
1599
  y: attrs.scaleY,
1024
1600
  };
1025
1601
  }
1602
+ /**
1603
+ * get absolute rotation of the node which takes into
1604
+ * account its ancestor rotations
1605
+ * @method
1606
+ * @name Konva.Node#getAbsoluteRotation
1607
+ * @returns {Number}
1608
+ * @example
1609
+ * // get absolute rotation
1610
+ * var rotation = node.getAbsoluteRotation();
1611
+ */
1026
1612
  getAbsoluteRotation() {
1027
1613
  return this.getAbsoluteTransform().decompose().rotation;
1028
1614
  }
1615
+ /**
1616
+ * get transform of the node
1617
+ * @method
1618
+ * @name Konva.Node#getTransform
1619
+ * @returns {Konva.Transform}
1620
+ */
1029
1621
  getTransform() {
1030
1622
  return this._getCache(TRANSFORM, this._getTransform);
1031
1623
  }
1032
1624
  _getTransform() {
1033
1625
  var _a, _b;
1034
- const m = this._cache.get(TRANSFORM) || new Transform();
1626
+ const m = this._cache[TRANSFORM] || new Transform();
1035
1627
  m.reset();
1628
+ // I was trying to use attributes directly here
1629
+ // but it doesn't work for Transformer well
1630
+ // because it overwrite x,y getters
1036
1631
  const x = this.x(), y = this.y(), rotation = Konva.getAngle(this.rotation()), scaleX = (_a = this.attrs.scaleX) !== null && _a !== void 0 ? _a : 1, scaleY = (_b = this.attrs.scaleY) !== null && _b !== void 0 ? _b : 1, skewX = this.attrs.skewX || 0, skewY = this.attrs.skewY || 0, offsetX = this.attrs.offsetX || 0, offsetY = this.attrs.offsetY || 0;
1037
1632
  if (x !== 0 || y !== 0) {
1038
1633
  m.translate(x, y);
@@ -1052,18 +1647,43 @@ export class Node {
1052
1647
  m.dirty = false;
1053
1648
  return m;
1054
1649
  }
1650
+ /**
1651
+ * clone node. Returns a new Node instance with identical attributes. You can also override
1652
+ * the node properties with an object literal, enabling you to use an existing node as a template
1653
+ * for another node
1654
+ * @method
1655
+ * @name Konva.Node#clone
1656
+ * @param {Object} obj override attrs
1657
+ * @returns {Konva.Node}
1658
+ * @example
1659
+ * // simple clone
1660
+ * var clone = node.clone();
1661
+ *
1662
+ * // clone a node and override the x position
1663
+ * var clone = rect.clone({
1664
+ * x: 5
1665
+ * });
1666
+ */
1055
1667
  clone(obj) {
1668
+ // instantiate new node
1056
1669
  let attrs = Util.cloneObject(this.attrs), key, allListeners, len, n, listener;
1670
+ // apply attr overrides
1057
1671
  for (key in obj) {
1058
1672
  attrs[key] = obj[key];
1059
1673
  }
1060
1674
  const node = new this.constructor(attrs);
1675
+ // copy over listeners
1061
1676
  for (key in this.eventListeners) {
1062
1677
  allListeners = this.eventListeners[key];
1063
1678
  len = allListeners.length;
1064
1679
  for (n = 0; n < len; n++) {
1065
1680
  listener = allListeners[n];
1681
+ /*
1682
+ * don't include konva namespaced listeners because
1683
+ * these are generated by the constructors
1684
+ */
1066
1685
  if (listener.name.indexOf(KONVA) < 0) {
1686
+ // if listeners array doesn't exist, then create it
1067
1687
  if (!node.eventListeners[key]) {
1068
1688
  node.eventListeners[key] = [];
1069
1689
  }
@@ -1075,7 +1695,17 @@ export class Node {
1075
1695
  }
1076
1696
  _toKonvaCanvas(config) {
1077
1697
  config = config || {};
1078
- const box = this.getClientRect();
1698
+ // the client rect is only needed for the parts of the box not configured
1699
+ const needsBox = config.x === undefined ||
1700
+ config.y === undefined ||
1701
+ !config.width ||
1702
+ !config.height;
1703
+ const box = needsBox
1704
+ ? this.getClientRect()
1705
+ : { x: 0, y: 0, width: 0, height: 0 };
1706
+ if (!isFinite(box.x + box.y + box.width + box.height)) {
1707
+ Util.error(`Cannot find the bounds of the node to export, its client rect is ${box.x}, ${box.y}, ${box.width}x${box.height}. Check its position, size and points.`);
1708
+ }
1079
1709
  const stage = this.getStage(), x = config.x !== undefined ? config.x : Math.floor(box.x), y = config.y !== undefined ? config.y : Math.floor(box.y), pixelRatio = config.pixelRatio || 1, canvas = new SceneCanvas({
1080
1710
  width: config.width || Math.ceil(box.width) || (stage ? stage.width() : 0),
1081
1711
  height: config.height ||
@@ -1083,11 +1713,7 @@ export class Node {
1083
1713
  (stage ? stage.height() : 0),
1084
1714
  pixelRatio: pixelRatio,
1085
1715
  }), context = canvas.getContext();
1086
- const bufferCanvas = new SceneCanvas({
1087
- width: canvas.width / canvas.pixelRatio + Math.abs(x),
1088
- height: canvas.height / canvas.pixelRatio + Math.abs(y),
1089
- pixelRatio: canvas.pixelRatio,
1090
- });
1716
+ const bufferCanvas = createBufferCanvas(canvas, x, y);
1091
1717
  if (config.imageSmoothingEnabled === false) {
1092
1718
  context._context.imageSmoothingEnabled = false;
1093
1719
  }
@@ -1097,11 +1723,54 @@ export class Node {
1097
1723
  }
1098
1724
  this.drawScene(canvas, undefined, bufferCanvas);
1099
1725
  context.restore();
1726
+ // the buffer is only needed while drawing
1727
+ Util.releaseCanvas(bufferCanvas._canvas);
1100
1728
  return canvas;
1101
1729
  }
1730
+ /**
1731
+ * converts node into an canvas element.
1732
+ * @method
1733
+ * @name Konva.Node#toCanvas
1734
+ * @param {Object} config
1735
+ * @param {Function} config.callback function executed when the composite has completed
1736
+ * @param {Number} [config.x] x position of canvas section
1737
+ * @param {Number} [config.y] y position of canvas section
1738
+ * @param {Number} [config.width] width of canvas section
1739
+ * @param {Number} [config.height] height of canvas section
1740
+ * @param {Number} [config.pixelRatio] pixelRatio of output canvas. Default is 1.
1741
+ * You can use that property to increase quality of the image, for example for super hight quality exports
1742
+ * or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
1743
+ * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1744
+ * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1745
+ * @example
1746
+ * var canvas = node.toCanvas();
1747
+ */
1102
1748
  toCanvas(config) {
1103
1749
  return this._toKonvaCanvas(config)._canvas;
1104
1750
  }
1751
+ /**
1752
+ * Creates a composite data URL (base64 string). If MIME type is not
1753
+ * specified, then "image/png" will result. For "image/jpeg", specify a quality
1754
+ * level as quality (range 0.0 - 1.0)
1755
+ * @method
1756
+ * @name Konva.Node#toDataURL
1757
+ * @param {Object} config
1758
+ * @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
1759
+ * "image/png" is the default
1760
+ * @param {Number} [config.x] x position of canvas section
1761
+ * @param {Number} [config.y] y position of canvas section
1762
+ * @param {Number} [config.width] width of canvas section
1763
+ * @param {Number} [config.height] height of canvas section
1764
+ * @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
1765
+ * you can specify the quality from 0 to 1, where 0 is very poor quality and 1
1766
+ * is very high quality
1767
+ * @param {Number} [config.pixelRatio] pixelRatio of output image url. Default is 1.
1768
+ * You can use that property to increase quality of the image, for example for super hight quality exports
1769
+ * or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
1770
+ * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1771
+ * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1772
+ * @returns {String}
1773
+ */
1105
1774
  toDataURL(config) {
1106
1775
  config = config || {};
1107
1776
  const mimeType = config.mimeType || null, quality = config.quality || null;
@@ -1111,6 +1780,37 @@ export class Node {
1111
1780
  }
1112
1781
  return url;
1113
1782
  }
1783
+ /**
1784
+ * converts node into an image. Since the toImage
1785
+ * method is asynchronous, the resulting image can only be retrieved from the config callback
1786
+ * or the returned Promise. toImage is most commonly used
1787
+ * to cache complex drawings as an image so that they don't have to constantly be redrawn
1788
+ * @method
1789
+ * @name Konva.Node#toImage
1790
+ * @param {Object} config
1791
+ * @param {Function} [config.callback] function executed when the composite has completed
1792
+ * @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
1793
+ * "image/png" is the default
1794
+ * @param {Number} [config.x] x position of canvas section
1795
+ * @param {Number} [config.y] y position of canvas section
1796
+ * @param {Number} [config.width] width of canvas section
1797
+ * @param {Number} [config.height] height of canvas section
1798
+ * @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
1799
+ * you can specify the quality from 0 to 1, where 0 is very poor quality and 1
1800
+ * is very high quality
1801
+ * @param {Number} [config.pixelRatio] pixelRatio of output image. Default is 1.
1802
+ * You can use that property to increase quality of the image, for example for super hight quality exports
1803
+ * or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
1804
+ * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1805
+ * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1806
+ * @return {Promise<Image>}
1807
+ * @example
1808
+ * var image = node.toImage({
1809
+ * callback(img) {
1810
+ * // do stuff with img
1811
+ * }
1812
+ * });
1813
+ */
1114
1814
  toImage(config) {
1115
1815
  return new Promise((resolve, reject) => {
1116
1816
  try {
@@ -1127,6 +1827,27 @@ export class Node {
1127
1827
  }
1128
1828
  });
1129
1829
  }
1830
+ /**
1831
+ * Converts node into a blob. Since the toBlob method is asynchronous,
1832
+ * the resulting blob can only be retrieved from the config callback
1833
+ * or the returned Promise.
1834
+ * @method
1835
+ * @name Konva.Node#toBlob
1836
+ * @param {Object} config
1837
+ * @param {Function} [config.callback] function executed when the composite has completed
1838
+ * @param {Number} [config.x] x position of canvas section
1839
+ * @param {Number} [config.y] y position of canvas section
1840
+ * @param {Number} [config.width] width of canvas section
1841
+ * @param {Number} [config.height] height of canvas section
1842
+ * @param {Number} [config.pixelRatio] pixelRatio of output canvas. Default is 1.
1843
+ * You can use that property to increase quality of the image, for example for super hight quality exports
1844
+ * or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
1845
+ * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1846
+ * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1847
+ * @example
1848
+ * var blob = await node.toBlob({});
1849
+ * @returns {Promise<Blob>} rejects if the canvas can not be encoded
1850
+ */
1130
1851
  toBlob(config) {
1131
1852
  return new Promise((resolve, reject) => {
1132
1853
  try {
@@ -1134,6 +1855,11 @@ export class Node {
1134
1855
  if (callback)
1135
1856
  delete config.callback;
1136
1857
  this.toCanvas(config).toBlob((blob) => {
1858
+ // the canvas reports a failed encode by passing null
1859
+ if (!blob) {
1860
+ reject(new Error('Konva: toBlob() failed, the canvas was not encoded'));
1861
+ return;
1862
+ }
1137
1863
  resolve(blob);
1138
1864
  callback === null || callback === void 0 ? void 0 : callback(blob);
1139
1865
  }, config === null || config === void 0 ? void 0 : config.mimeType, config === null || config === void 0 ? void 0 : config.quality);
@@ -1154,13 +1880,26 @@ export class Node {
1154
1880
  height: this.height(),
1155
1881
  };
1156
1882
  }
1883
+ /**
1884
+ * get class name, which may return Stage, Layer, Group, or shape class names like Rect, Circle, Text, etc.
1885
+ * @method
1886
+ * @name Konva.Node#getClassName
1887
+ * @returns {String}
1888
+ */
1157
1889
  getClassName() {
1158
1890
  return this.className || this.nodeType;
1159
1891
  }
1892
+ /**
1893
+ * get the node type, which may return Stage, Layer, Group, or Shape
1894
+ * @method
1895
+ * @name Konva.Node#getType
1896
+ * @returns {String}
1897
+ */
1160
1898
  getType() {
1161
1899
  return this.nodeType;
1162
1900
  }
1163
1901
  getDragDistance() {
1902
+ // compare with undefined because we need to track 0 value
1164
1903
  if (this.attrs.dragDistance !== undefined) {
1165
1904
  return this.attrs.dragDistance;
1166
1905
  }
@@ -1176,6 +1915,10 @@ export class Node {
1176
1915
  for (i = 0; i < evtListeners.length; i++) {
1177
1916
  evtName = evtListeners[i].name;
1178
1917
  handler = evtListeners[i].handler;
1918
+ // the following two conditions must be true in order to remove a handler:
1919
+ // 1) the current event name cannot be konva unless the event name is konva
1920
+ // this enables developers to force remove a konva specific listener for whatever reason
1921
+ // 2) an event name is not specified, or if one is specified, it matches the current event name
1179
1922
  if ((evtName !== 'konva' || name === 'konva') &&
1180
1923
  (!name || evtName === name) &&
1181
1924
  (!callback || callback === handler)) {
@@ -1194,6 +1937,17 @@ export class Node {
1194
1937
  newVal: newVal,
1195
1938
  });
1196
1939
  }
1940
+ /**
1941
+ * add name to node
1942
+ * @method
1943
+ * @name Konva.Node#addName
1944
+ * @param {String} name
1945
+ * @returns {Konva.Node}
1946
+ * @example
1947
+ * node.name('red');
1948
+ * node.addName('selected');
1949
+ * node.name(); // return 'red selected'
1950
+ */
1197
1951
  addName(name) {
1198
1952
  if (!this.hasName(name)) {
1199
1953
  const oldName = this.name();
@@ -1202,6 +1956,18 @@ export class Node {
1202
1956
  }
1203
1957
  return this;
1204
1958
  }
1959
+ /**
1960
+ * check is node has name
1961
+ * @method
1962
+ * @name Konva.Node#hasName
1963
+ * @param {String} name
1964
+ * @returns {Boolean}
1965
+ * @example
1966
+ * node.name('red');
1967
+ * node.hasName('red'); // return true
1968
+ * node.hasName('selected'); // return false
1969
+ * node.hasName(''); // return false
1970
+ */
1205
1971
  hasName(name) {
1206
1972
  if (!name) {
1207
1973
  return false;
@@ -1210,9 +1976,22 @@ export class Node {
1210
1976
  if (!fullName) {
1211
1977
  return false;
1212
1978
  }
1979
+ // if name is '' the "names" will be [''], so I added extra check above
1213
1980
  const names = (fullName || '').split(/\s/g);
1214
1981
  return names.indexOf(name) !== -1;
1215
1982
  }
1983
+ /**
1984
+ * remove name from node
1985
+ * @method
1986
+ * @name Konva.Node#removeName
1987
+ * @param {String} name
1988
+ * @returns {Konva.Node}
1989
+ * @example
1990
+ * node.name('red selected');
1991
+ * node.removeName('selected');
1992
+ * node.hasName('selected'); // return false
1993
+ * node.name(); // return 'red'
1994
+ */
1216
1995
  removeName(name) {
1217
1996
  const names = (this.name() || '').split(/\s/g);
1218
1997
  const index = names.indexOf(name);
@@ -1222,12 +2001,23 @@ export class Node {
1222
2001
  }
1223
2002
  return this;
1224
2003
  }
2004
+ /**
2005
+ * set attr
2006
+ * @method
2007
+ * @name Konva.Node#setAttr
2008
+ * @param {String} attr
2009
+ * @param {*} val
2010
+ * @returns {Konva.Node}
2011
+ * @example
2012
+ * node.setAttr('x', 5);
2013
+ */
1225
2014
  setAttr(attr, val) {
1226
2015
  const func = this[SET + Util._capitalize(attr)];
1227
2016
  if (Util._isFunction(func)) {
1228
2017
  func.call(this, val);
1229
2018
  }
1230
2019
  else {
2020
+ // otherwise set directly
1231
2021
  this._setAttr(attr, val);
1232
2022
  }
1233
2023
  return this;
@@ -1249,42 +2039,27 @@ export class Node {
1249
2039
  else {
1250
2040
  this.attrs[key] = val;
1251
2041
  }
2042
+ if (this._attrsVersion !== undefined)
2043
+ this._attrsVersion++;
1252
2044
  if (this._shouldFireChangeEvents) {
1253
2045
  this._fireChangeEvent(key, oldVal, val);
1254
2046
  }
1255
2047
  this._requestDraw();
1256
2048
  }
1257
- _setComponentAttr(key, component, val) {
1258
- let oldVal;
1259
- if (val !== undefined) {
1260
- oldVal = this.attrs[key];
1261
- if (!oldVal) {
1262
- this.attrs[key] = this.getAttr(key);
1263
- }
1264
- this.attrs[key][component] = val;
1265
- this._fireChangeEvent(key, oldVal, val);
1266
- }
1267
- }
1268
2049
  _fireAndBubble(eventType, evt, compareShape) {
1269
2050
  if (evt && this.nodeType === SHAPE) {
1270
2051
  evt.target = this;
1271
2052
  }
1272
- const nonBubbling = [
1273
- MOUSEENTER,
1274
- MOUSELEAVE,
1275
- POINTERENTER,
1276
- POINTERLEAVE,
1277
- TOUCHENTER,
1278
- TOUCHLEAVE,
1279
- ];
1280
- const shouldStop = nonBubbling.indexOf(eventType) !== -1 &&
2053
+ const nonBubbling = NON_BUBBLING_EVENTS.indexOf(eventType) !== -1;
2054
+ const shouldStop = nonBubbling &&
1281
2055
  ((compareShape &&
1282
2056
  (this === compareShape ||
1283
2057
  (this.isAncestorOf && this.isAncestorOf(compareShape)))) ||
1284
2058
  (this.nodeType === 'Stage' && !compareShape));
1285
2059
  if (!shouldStop) {
1286
2060
  this._fire(eventType, evt);
1287
- const stopBubble = nonBubbling.indexOf(eventType) !== -1 &&
2061
+ // simulate event bubbling
2062
+ const stopBubble = nonBubbling &&
1288
2063
  compareShape &&
1289
2064
  compareShape.isAncestorOf &&
1290
2065
  compareShape.isAncestorOf(this) &&
@@ -1304,11 +2079,19 @@ export class Node {
1304
2079
  }
1305
2080
  _getProtoListeners(eventType) {
1306
2081
  var _a, _b;
1307
- const { nodeType } = this;
1308
- const allListeners = Node.protoListenerMap.get(nodeType) || {};
1309
- let events = allListeners === null || allListeners === void 0 ? void 0 : allListeners[eventType];
2082
+ const proto = Object.getPrototypeOf(this);
2083
+ let allListeners = Node.protoListenerMap.get(proto);
2084
+ if (!allListeners) {
2085
+ allListeners = {};
2086
+ Node.protoListenerMap.set(proto, allListeners);
2087
+ }
2088
+ let events = allListeners[eventType];
1310
2089
  if (events === undefined) {
2090
+ //recalculate cache
1311
2091
  events = [];
2092
+ // Dedupe across the prototype chain: subclasses without their own
2093
+ // `eventListeners` inherit the parent's, so a single handler would
2094
+ // otherwise be pushed once per chain level (Stage→Container→Node = 3x).
1312
2095
  const seen = new Set();
1313
2096
  let obj = Object.getPrototypeOf(this);
1314
2097
  while (obj) {
@@ -1322,8 +2105,8 @@ export class Node {
1322
2105
  }
1323
2106
  obj = Object.getPrototypeOf(obj);
1324
2107
  }
2108
+ // update cache
1325
2109
  allListeners[eventType] = events;
1326
- Node.protoListenerMap.set(nodeType, allListeners);
1327
2110
  }
1328
2111
  return events;
1329
2112
  }
@@ -1333,10 +2116,15 @@ export class Node {
1333
2116
  evt.type = eventType;
1334
2117
  const topListeners = this._getProtoListeners(eventType);
1335
2118
  if (topListeners) {
2119
+ // The list is rebuilt when a prototype gains a listener, so no
2120
+ // defensive .slice() needed (hot path: every *Change).
1336
2121
  for (let i = 0; i < topListeners.length; i++) {
1337
2122
  topListeners[i].handler.call(this, evt);
1338
2123
  }
1339
2124
  }
2125
+ // snapshot prevents skipping listeners when a handler mutates the array
2126
+ // (e.g. off + on for the same event), but we also need to fire listeners
2127
+ // added during dispatch (e.g. draggable(true) inside mousedown)
1340
2128
  const selfListeners = this.eventListeners[eventType];
1341
2129
  if (selfListeners) {
1342
2130
  const list = selfListeners.slice();
@@ -1344,6 +2132,7 @@ export class Node {
1344
2132
  for (let i = 0; i < list.length; i++) {
1345
2133
  list[i].handler.call(this, evt);
1346
2134
  }
2135
+ // fire any listeners appended during dispatch
1347
2136
  const liveListeners = this.eventListeners[eventType];
1348
2137
  if (liveListeners) {
1349
2138
  for (let i = origLen; i < liveListeners.length; i++) {
@@ -1352,11 +2141,18 @@ export class Node {
1352
2141
  }
1353
2142
  }
1354
2143
  }
2144
+ /**
2145
+ * draw both scene and hit graphs. If the node being drawn is the stage, all of the layers will be cleared and redrawn
2146
+ * @method
2147
+ * @name Konva.Node#draw
2148
+ * @returns {Konva.Node}
2149
+ */
1355
2150
  draw() {
1356
2151
  this.drawScene();
1357
2152
  this.drawHit();
1358
2153
  return this;
1359
2154
  }
2155
+ // drag & drop
1360
2156
  _createDragElement(evt) {
1361
2157
  const pointerId = evt ? evt.pointerId : undefined;
1362
2158
  const stage = this.getStage();
@@ -1379,15 +2175,26 @@ export class Node {
1379
2175
  startEvent: evt,
1380
2176
  });
1381
2177
  }
2178
+ /**
2179
+ * initiate drag and drop.
2180
+ * @method
2181
+ * @name Konva.Node#startDrag
2182
+ */
1382
2183
  startDrag(evt, bubbleEvent = true) {
1383
2184
  if (!DD._dragElements.has(this._id)) {
1384
2185
  this._createDragElement(evt);
1385
2186
  }
1386
2187
  const elem = DD._dragElements.get(this._id);
2188
+ // a node outside of a stage has no pointer to follow
2189
+ if (!elem) {
2190
+ return;
2191
+ }
1387
2192
  elem.dragStatus = 'dragging';
1388
2193
  this.fire('dragstart', {
1389
2194
  type: 'dragstart',
1390
2195
  target: this,
2196
+ // Use the stored start event if available (from mousedown/touchstart),
2197
+ // otherwise fall back to the provided event (when startDrag is called programmatically)
1391
2198
  evt: (elem.startEvent && elem.startEvent.evt) || (evt && evt.evt),
1392
2199
  }, bubbleEvent);
1393
2200
  }
@@ -1406,18 +2213,26 @@ export class Node {
1406
2213
  if (!bounded) {
1407
2214
  Util.warn('dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.');
1408
2215
  }
2216
+ else if (!Util._isNumber(bounded.x) || !Util._isNumber(bounded.y)) {
2217
+ Util.warn(`dragBoundFunc returned a position with a non-finite x or y (${bounded.x}, ${bounded.y}). The node was not moved.`);
2218
+ return;
2219
+ }
1409
2220
  else {
1410
2221
  newNodePos = bounded;
1411
2222
  }
1412
2223
  }
1413
- if (!this._lastPos ||
1414
- this._lastPos.x !== newNodePos.x ||
1415
- this._lastPos.y !== newNodePos.y) {
2224
+ const lastPos = elem.lastPos;
2225
+ if (!lastPos || lastPos.x !== newNodePos.x || lastPos.y !== newNodePos.y) {
1416
2226
  this.setAbsolutePosition(newNodePos);
1417
2227
  this._requestDraw();
1418
2228
  }
1419
- this._lastPos = newNodePos;
2229
+ elem.lastPos = newNodePos;
1420
2230
  }
2231
+ /**
2232
+ * stop drag and drop
2233
+ * @method
2234
+ * @name Konva.Node#stopDrag
2235
+ */
1421
2236
  stopDrag(evt) {
1422
2237
  const elem = DD._dragElements.get(this._id);
1423
2238
  if (elem) {
@@ -1430,6 +2245,11 @@ export class Node {
1430
2245
  this._setAttr('draggable', draggable);
1431
2246
  this._dragChange();
1432
2247
  }
2248
+ /**
2249
+ * determine if node is currently in drag and drop mode
2250
+ * @method
2251
+ * @name Konva.Node#isDragging
2252
+ */
1433
2253
  isDragging() {
1434
2254
  const elem = DD._dragElements.get(this._id);
1435
2255
  return elem ? elem.dragStatus === 'dragging' : false;
@@ -1451,6 +2271,8 @@ export class Node {
1451
2271
  hasDraggingChild = true;
1452
2272
  }
1453
2273
  });
2274
+ // nested drag can be started
2275
+ // in that case we don't need to start new drag
1454
2276
  if (!hasDraggingChild) {
1455
2277
  this._createDragElement(evt);
1456
2278
  }
@@ -1461,7 +2283,13 @@ export class Node {
1461
2283
  this._listenDrag();
1462
2284
  }
1463
2285
  else {
2286
+ // remove event listeners
1464
2287
  this._dragCleanup();
2288
+ /*
2289
+ * force drag and drop to end
2290
+ * if this node is currently in
2291
+ * drag and drop mode
2292
+ */
1465
2293
  const stage = this.getStage();
1466
2294
  if (!stage) {
1467
2295
  return;
@@ -1481,6 +2309,21 @@ export class Node {
1481
2309
  this.off('mousedown.konva');
1482
2310
  this.off('touchstart.konva');
1483
2311
  }
2312
+ /**
2313
+ * determine if node (at least partially) is currently in user-visible area
2314
+ * @method
2315
+ * @param {(Number | Object)} margin optional margin in pixels
2316
+ * @param {Number} margin.x
2317
+ * @param {Number} margin.y
2318
+ * @returns {Boolean}
2319
+ * @name Konva.Node#isClientRectOnScreen
2320
+ * @example
2321
+ * // get index
2322
+ * // default calculations
2323
+ * var isOnScreen = node.isClientRectOnScreen()
2324
+ * // increase object size (or screen size) for cases when objects close to the screen still need to be marked as "visible"
2325
+ * var isOnScreen = node.isClientRectOnScreen({ x: stage.width(), y: stage.height() })
2326
+ */
1484
2327
  isClientRectOnScreen(margin = { x: 0, y: 0 }) {
1485
2328
  const stage = this.getStage();
1486
2329
  if (!stage) {
@@ -1494,6 +2337,20 @@ export class Node {
1494
2337
  };
1495
2338
  return Util.haveIntersection(screenRect, this.getClientRect());
1496
2339
  }
2340
+ /**
2341
+ * create node with JSON string or an Object. Deserialization restores attributes only,
2342
+ * not functions, images or event handlers (that would make the serialized object huge):
2343
+ * `sceneFunc`/`hitFunc` of custom shapes, images and `fillPatternImage`, `clipFunc`,
2344
+ * `dragBoundFunc`, filter functions, the `nodes`, `boundBoxFunc` and `anchorStyleFunc`
2345
+ * of a Transformer, typed arrays and the `cache()` state. If your app uses them (it probably
2346
+ * does), select the nodes after loading the stage and set these properties again with
2347
+ * `on()`, `sceneFunc()`, `image()` and so on
2348
+ * @method
2349
+ * @memberof Konva.Node
2350
+ * @param {String|Object} data string or object
2351
+ * @param {Element} [container] optional container dom element used only if you're
2352
+ * creating a stage node
2353
+ */
1497
2354
  static create(data, container) {
1498
2355
  if (Util._isString(data)) {
1499
2356
  data = JSON.parse(data);
@@ -1502,6 +2359,7 @@ export class Node {
1502
2359
  }
1503
2360
  static _createNode(obj, container) {
1504
2361
  let className = Node.prototype.getClassName.call(obj), children = obj.children, no, len, n;
2362
+ // if container was passed in, add it to attrs
1505
2363
  if (container) {
1506
2364
  obj.attrs.container = container;
1507
2365
  }
@@ -1522,12 +2380,19 @@ export class Node {
1522
2380
  return no;
1523
2381
  }
1524
2382
  }
2383
+ // Perf: lets a listener inside an absoluteTransform cascade (e.g. Konva
2384
+ // .Transformer reacting to a stage drag fan-out across N attached nodes)
2385
+ // defer work until the cascade ends — collapses O(N) listener-driven calls
2386
+ // into one. Counter is mutated by Container's _clearSelfAndDescendantCache.
1525
2387
  Node._absTransformCascadeDepth = 0;
1526
2388
  Node._pendingAfterCascade = [];
1527
- Node.protoListenerMap = new Map();
2389
+ // keyed by prototype: subclasses that share a nodeType (every shape class)
2390
+ // have their own listeners
2391
+ Node.protoListenerMap = new WeakMap();
1528
2392
  Node.prototype.nodeType = 'Node';
1529
2393
  Node.prototype._attrsAffectingSize = [];
1530
- Node.prototype.eventListeners = {};
2394
+ // attache events listeners once into prototype
2395
+ // that way we don't spend too much time on making an new instance
1531
2396
  Node.prototype.on(TRANSFORM_CHANGE_STR, function () {
1532
2397
  if (this._batchingTransformChange) {
1533
2398
  this._needClearTransformCache = true;
@@ -1546,38 +2411,516 @@ Node.prototype.on('opacityChange.konva', function () {
1546
2411
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
1547
2412
  });
1548
2413
  const addGetterSetter = Factory.addGetterSetter;
2414
+ /**
2415
+ * get/set zIndex relative to the node's siblings who share the same parent.
2416
+ * Please remember that zIndex is not absolute (like in CSS). It is relative to parent element only.
2417
+ * @name Konva.Node#zIndex
2418
+ * @method
2419
+ * @param {Number} index
2420
+ * @returns {Number}
2421
+ * @example
2422
+ * // get index
2423
+ * var index = node.zIndex();
2424
+ *
2425
+ * // set index
2426
+ * node.zIndex(2);
2427
+ */
1549
2428
  addGetterSetter(Node, 'zIndex');
2429
+ /**
2430
+ * get/set node absolute position
2431
+ * @name Konva.Node#absolutePosition
2432
+ * @method
2433
+ * @param {Object} pos
2434
+ * @param {Number} pos.x
2435
+ * @param {Number} pos.y
2436
+ * @returns {Object}
2437
+ * @example
2438
+ * // get position
2439
+ * var position = node.absolutePosition();
2440
+ *
2441
+ * // set position
2442
+ * node.absolutePosition({
2443
+ * x: 5,
2444
+ * y: 10
2445
+ * });
2446
+ */
1550
2447
  addGetterSetter(Node, 'absolutePosition');
1551
2448
  addGetterSetter(Node, 'position');
2449
+ /**
2450
+ * get/set node position relative to parent
2451
+ * @name Konva.Node#position
2452
+ * @method
2453
+ * @param {Object} pos
2454
+ * @param {Number} pos.x
2455
+ * @param {Number} pos.y
2456
+ * @returns {Object}
2457
+ * @example
2458
+ * // get position
2459
+ * var position = node.position();
2460
+ *
2461
+ * // set position
2462
+ * node.position({
2463
+ * x: 5,
2464
+ * y: 10
2465
+ * });
2466
+ */
1552
2467
  addGetterSetter(Node, 'x', 0, getNumberValidator());
2468
+ /**
2469
+ * get/set x position
2470
+ * @name Konva.Node#x
2471
+ * @method
2472
+ * @param {Number} x
2473
+ * @returns {Object}
2474
+ * @example
2475
+ * // get x
2476
+ * var x = node.x();
2477
+ *
2478
+ * // set x
2479
+ * node.x(5);
2480
+ */
1553
2481
  addGetterSetter(Node, 'y', 0, getNumberValidator());
2482
+ /**
2483
+ * get/set y position
2484
+ * @name Konva.Node#y
2485
+ * @method
2486
+ * @param {Number} y
2487
+ * @returns {Integer}
2488
+ * @example
2489
+ * // get y
2490
+ * var y = node.y();
2491
+ *
2492
+ * // set y
2493
+ * node.y(5);
2494
+ */
1554
2495
  addGetterSetter(Node, 'globalCompositeOperation', 'source-over', getStringValidator());
2496
+ /**
2497
+ * get/set globalCompositeOperation of a node. globalCompositeOperation DOESN'T affect hit graph of nodes. So they are still trigger to events as they have default "source-over" globalCompositeOperation.
2498
+ * @name Konva.Node#globalCompositeOperation
2499
+ * @method
2500
+ * @param {String} type
2501
+ * @returns {String}
2502
+ * @example
2503
+ * // get globalCompositeOperation
2504
+ * var globalCompositeOperation = shape.globalCompositeOperation();
2505
+ *
2506
+ * // set globalCompositeOperation
2507
+ * shape.globalCompositeOperation('source-in');
2508
+ */
1555
2509
  addGetterSetter(Node, 'opacity', 1, getNumberValidator());
2510
+ /**
2511
+ * get/set opacity. Opacity values range from 0 to 1.
2512
+ * A node with an opacity of 0 is fully transparent, and a node
2513
+ * with an opacity of 1 is fully opaque
2514
+ * @name Konva.Node#opacity
2515
+ * @method
2516
+ * @param {Object} opacity
2517
+ * @returns {Number}
2518
+ * @example
2519
+ * // get opacity
2520
+ * var opacity = node.opacity();
2521
+ *
2522
+ * // set opacity
2523
+ * node.opacity(0.5);
2524
+ */
1556
2525
  addGetterSetter(Node, 'name', '', getStringValidator());
2526
+ /**
2527
+ * get/set name.
2528
+ * @name Konva.Node#name
2529
+ * @method
2530
+ * @param {String} name
2531
+ * @returns {String}
2532
+ * @example
2533
+ * // get name
2534
+ * var name = node.name();
2535
+ *
2536
+ * // set name
2537
+ * node.name('foo');
2538
+ *
2539
+ * // also node may have multiple names (as css classes)
2540
+ * node.name('foo bar');
2541
+ */
1557
2542
  addGetterSetter(Node, 'id', '', getStringValidator());
2543
+ /**
2544
+ * get/set id. Id is global for whole page.
2545
+ * @name Konva.Node#id
2546
+ * @method
2547
+ * @param {String} id
2548
+ * @returns {String}
2549
+ * @example
2550
+ * // get id
2551
+ * var name = node.id();
2552
+ *
2553
+ * // set id
2554
+ * node.id('foo');
2555
+ */
1558
2556
  addGetterSetter(Node, 'rotation', 0, getNumberValidator());
2557
+ /**
2558
+ * get/set rotation in degrees
2559
+ * @name Konva.Node#rotation
2560
+ * @method
2561
+ * @param {Number} rotation
2562
+ * @returns {Number}
2563
+ * @example
2564
+ * // get rotation in degrees
2565
+ * var rotation = node.rotation();
2566
+ *
2567
+ * // set rotation in degrees
2568
+ * node.rotation(45);
2569
+ */
1559
2570
  Factory.addComponentsGetterSetter(Node, 'scale', ['x', 'y']);
2571
+ /**
2572
+ * get/set scale
2573
+ * @name Konva.Node#scale
2574
+ * @param {Object} scale
2575
+ * @param {Number} scale.x
2576
+ * @param {Number} scale.y
2577
+ * @method
2578
+ * @returns {Object}
2579
+ * @example
2580
+ * // get scale
2581
+ * var scale = node.scale();
2582
+ *
2583
+ * // set scale
2584
+ * shape.scale({
2585
+ * x: 2,
2586
+ * y: 3
2587
+ * });
2588
+ */
1560
2589
  addGetterSetter(Node, 'scaleX', 1, getNumberValidator());
2590
+ /**
2591
+ * get/set scale x
2592
+ * @name Konva.Node#scaleX
2593
+ * @param {Number} x
2594
+ * @method
2595
+ * @returns {Number}
2596
+ * @example
2597
+ * // get scale x
2598
+ * var scaleX = node.scaleX();
2599
+ *
2600
+ * // set scale x
2601
+ * node.scaleX(2);
2602
+ */
1561
2603
  addGetterSetter(Node, 'scaleY', 1, getNumberValidator());
2604
+ /**
2605
+ * get/set scale y
2606
+ * @name Konva.Node#scaleY
2607
+ * @param {Number} y
2608
+ * @method
2609
+ * @returns {Number}
2610
+ * @example
2611
+ * // get scale y
2612
+ * var scaleY = node.scaleY();
2613
+ *
2614
+ * // set scale y
2615
+ * node.scaleY(2);
2616
+ */
1562
2617
  Factory.addComponentsGetterSetter(Node, 'skew', ['x', 'y']);
2618
+ /**
2619
+ * get/set skew
2620
+ * @name Konva.Node#skew
2621
+ * @param {Object} skew
2622
+ * @param {Number} skew.x
2623
+ * @param {Number} skew.y
2624
+ * @method
2625
+ * @returns {Object}
2626
+ * @example
2627
+ * // get skew
2628
+ * var skew = node.skew();
2629
+ *
2630
+ * // set skew
2631
+ * node.skew({
2632
+ * x: 20,
2633
+ * y: 10
2634
+ * });
2635
+ */
1563
2636
  addGetterSetter(Node, 'skewX', 0, getNumberValidator());
2637
+ /**
2638
+ * get/set skew x
2639
+ * @name Konva.Node#skewX
2640
+ * @param {Number} x
2641
+ * @method
2642
+ * @returns {Number}
2643
+ * @example
2644
+ * // get skew x
2645
+ * var skewX = node.skewX();
2646
+ *
2647
+ * // set skew x
2648
+ * node.skewX(3);
2649
+ */
1564
2650
  addGetterSetter(Node, 'skewY', 0, getNumberValidator());
2651
+ /**
2652
+ * get/set skew y
2653
+ * @name Konva.Node#skewY
2654
+ * @param {Number} y
2655
+ * @method
2656
+ * @returns {Number}
2657
+ * @example
2658
+ * // get skew y
2659
+ * var skewY = node.skewY();
2660
+ *
2661
+ * // set skew y
2662
+ * node.skewY(3);
2663
+ */
1565
2664
  Factory.addComponentsGetterSetter(Node, 'offset', ['x', 'y']);
2665
+ /**
2666
+ * get/set offset. Offsets the default position and rotation point
2667
+ * @method
2668
+ * @param {Object} offset
2669
+ * @param {Number} offset.x
2670
+ * @param {Number} offset.y
2671
+ * @returns {Object}
2672
+ * @example
2673
+ * // get offset
2674
+ * var offset = node.offset();
2675
+ *
2676
+ * // set offset
2677
+ * node.offset({
2678
+ * x: 20,
2679
+ * y: 10
2680
+ * });
2681
+ */
1566
2682
  addGetterSetter(Node, 'offsetX', 0, getNumberValidator());
2683
+ /**
2684
+ * get/set offset x
2685
+ * @name Konva.Node#offsetX
2686
+ * @method
2687
+ * @param {Number} x
2688
+ * @returns {Number}
2689
+ * @example
2690
+ * // get offset x
2691
+ * var offsetX = node.offsetX();
2692
+ *
2693
+ * // set offset x
2694
+ * node.offsetX(3);
2695
+ */
1567
2696
  addGetterSetter(Node, 'offsetY', 0, getNumberValidator());
2697
+ /**
2698
+ * get/set offset y
2699
+ * @name Konva.Node#offsetY
2700
+ * @method
2701
+ * @param {Number} y
2702
+ * @returns {Number}
2703
+ * @example
2704
+ * // get offset y
2705
+ * var offsetY = node.offsetY();
2706
+ *
2707
+ * // set offset y
2708
+ * node.offsetY(3);
2709
+ */
1568
2710
  addGetterSetter(Node, 'dragDistance', undefined, getNumberValidator());
2711
+ /**
2712
+ * get/set drag distance. A drag starts once the pointer moved this far from where it
2713
+ * went down, on either axis. Default is `Konva.dragDistance`
2714
+ * @name Konva.Node#dragDistance
2715
+ * @method
2716
+ * @param {Number} distance
2717
+ * @returns {Number}
2718
+ * @example
2719
+ * // get drag distance
2720
+ * var dragDistance = node.dragDistance();
2721
+ *
2722
+ * // set distance
2723
+ * // node starts dragging only if pointer moved more then 3 pixels
2724
+ * node.dragDistance(3);
2725
+ * // or set globally
2726
+ * Konva.dragDistance = 3;
2727
+ */
1569
2728
  addGetterSetter(Node, 'width', 0, getNumberValidator());
2729
+ /**
2730
+ * get/set width
2731
+ * @name Konva.Node#width
2732
+ * @method
2733
+ * @param {Number} width
2734
+ * @returns {Number}
2735
+ * @example
2736
+ * // get width
2737
+ * var width = node.width();
2738
+ *
2739
+ * // set width
2740
+ * node.width(100);
2741
+ */
1570
2742
  addGetterSetter(Node, 'height', 0, getNumberValidator());
2743
+ /**
2744
+ * get/set height
2745
+ * @name Konva.Node#height
2746
+ * @method
2747
+ * @param {Number} height
2748
+ * @returns {Number}
2749
+ * @example
2750
+ * // get height
2751
+ * var height = node.height();
2752
+ *
2753
+ * // set height
2754
+ * node.height(100);
2755
+ */
1571
2756
  addGetterSetter(Node, 'listening', true, getBooleanValidator());
2757
+ /**
2758
+ * get/set listening attr. If you need to determine if a node is listening or not
2759
+ * by taking into account its parents, use the isListening() method
2760
+ * nodes with listening set to false will not be detected in hit graph
2761
+ * so they will be ignored in container.getIntersection() method
2762
+ * a non-listening layer (or a layer of a non-listening stage) also
2763
+ * releases its hit canvas, so it uses less memory
2764
+ * @name Konva.Node#listening
2765
+ * @method
2766
+ * @param {Boolean} listening Can be true, or false. The default is true.
2767
+ * @returns {Boolean}
2768
+ * @example
2769
+ * // get listening attr
2770
+ * var listening = node.listening();
2771
+ *
2772
+ * // stop listening for events, remove node and all its children from hit graph
2773
+ * node.listening(false);
2774
+ *
2775
+ * // listen to events according to the parent
2776
+ * node.listening(true);
2777
+ */
2778
+ /**
2779
+ * get/set preventDefault
2780
+ * By default all shapes will prevent default behavior
2781
+ * of a browser on a pointer move or tap.
2782
+ * that will prevent native scrolling when you are trying to drag&drop a node
2783
+ * but sometimes you may need to enable default actions
2784
+ * in that case you can set the property to false
2785
+ * @name Konva.Node#preventDefault
2786
+ * @method
2787
+ * @param {Boolean} preventDefault
2788
+ * @returns {Boolean}
2789
+ * @example
2790
+ * // get preventDefault
2791
+ * var shouldPrevent = shape.preventDefault();
2792
+ *
2793
+ * // set preventDefault
2794
+ * shape.preventDefault(false);
2795
+ */
1572
2796
  addGetterSetter(Node, 'preventDefault', true, getBooleanValidator());
1573
2797
  addGetterSetter(Node, 'filters', undefined, function (val) {
1574
2798
  this._filterUpToDate = false;
1575
2799
  return val;
1576
2800
  });
2801
+ /**
2802
+ * get/set filters. Supports function filters, CSS filter strings, or mixed arrays.
2803
+ * CSS filters are applied using native browser performance when possible, function filters use ImageData manipulation.
2804
+ * CSS filters automatically fall back to function filters in unsupported browsers.
2805
+ * @name Konva.Node#filters
2806
+ * @method
2807
+ * @param {Array} filters array of filter functions and/or CSS filter strings
2808
+ * @returns {Array}
2809
+ * @example
2810
+ * // get filters
2811
+ * var filters = node.filters();
2812
+ *
2813
+ * // set CSS filters only (no caching required, uses native performance)
2814
+ * node.filters(['blur(5px)', 'brightness(1.2)', 'contrast(1.5)']);
2815
+ *
2816
+ * // set function filters only (caching required)
2817
+ * node.cache();
2818
+ * node.filters([Konva.Filters.Blur, Konva.Filters.Sepia, Konva.Filters.Invert]);
2819
+ *
2820
+ * // mix CSS and function filters (caching required, uses fallback strategy)
2821
+ * node.cache();
2822
+ * node.filters([
2823
+ * 'blur(3px)', // CSS filter
2824
+ * Konva.Filters.Invert, // function filter
2825
+ * 'brightness(1.5)' // CSS filter
2826
+ * ]);
2827
+ */
1577
2828
  addGetterSetter(Node, 'visible', true, getBooleanValidator());
2829
+ /**
2830
+ * get/set visible attr. Can be true, or false. The default is true.
2831
+ * If you need to determine if a node is visible or not
2832
+ * by taking into account its parents, use the isVisible() method
2833
+ * @name Konva.Node#visible
2834
+ * @method
2835
+ * @param {Boolean} visible
2836
+ * @returns {Boolean}
2837
+ * @example
2838
+ * // get visible attr
2839
+ * var visible = node.visible();
2840
+ *
2841
+ * // make invisible
2842
+ * node.visible(false);
2843
+ *
2844
+ * // make visible (according to the parent)
2845
+ * node.visible(true);
2846
+ *
2847
+ */
1578
2848
  addGetterSetter(Node, 'transformsEnabled', 'all', getStringValidator());
2849
+ /**
2850
+ * get/set transforms that are enabled. Can be "all", "none", or "position". The default
2851
+ * is "all"
2852
+ * @name Konva.Node#transformsEnabled
2853
+ * @method
2854
+ * @param {String} enabled
2855
+ * @returns {String}
2856
+ * @example
2857
+ * // enable position transform only to improve draw performance
2858
+ * node.transformsEnabled('position');
2859
+ *
2860
+ * // enable all transforms
2861
+ * node.transformsEnabled('all');
2862
+ */
2863
+ /**
2864
+ * get/set node size
2865
+ * @name Konva.Node#size
2866
+ * @method
2867
+ * @param {Object} size
2868
+ * @param {Number} size.width
2869
+ * @param {Number} size.height
2870
+ * @returns {Object}
2871
+ * @example
2872
+ * // get node size
2873
+ * var size = node.size();
2874
+ * var width = size.width;
2875
+ * var height = size.height;
2876
+ *
2877
+ * // set size
2878
+ * node.size({
2879
+ * width: 100,
2880
+ * height: 200
2881
+ * });
2882
+ */
1579
2883
  addGetterSetter(Node, 'size');
2884
+ /**
2885
+ * get/set drag bound function. This is used to override the default
2886
+ * drag and drop position. The function is called with the absolute position
2887
+ * the node is about to get and the native event, and must return the
2888
+ * absolute position to use
2889
+ * @name Konva.Node#dragBoundFunc
2890
+ * @method
2891
+ * @param {Function} dragBoundFunc function(pos, evt) returning `{ x, y }`
2892
+ * @returns {Function}
2893
+ * @example
2894
+ * // get drag bound function
2895
+ * var dragBoundFunc = node.dragBoundFunc();
2896
+ *
2897
+ * // create vertical drag and drop
2898
+ * node.dragBoundFunc(function(pos){
2899
+ * // important pos - is absolute position of the node
2900
+ * // you should return absolute position too
2901
+ * return {
2902
+ * x: this.absolutePosition().x,
2903
+ * y: pos.y
2904
+ * };
2905
+ * });
2906
+ */
1580
2907
  addGetterSetter(Node, 'dragBoundFunc');
2908
+ /**
2909
+ * get/set draggable flag
2910
+ * @name Konva.Node#draggable
2911
+ * @method
2912
+ * @param {Boolean} draggable
2913
+ * @returns {Boolean}
2914
+ * @example
2915
+ * // get draggable flag
2916
+ * var draggable = node.draggable();
2917
+ *
2918
+ * // enable drag and drop
2919
+ * node.draggable(true);
2920
+ *
2921
+ * // disable drag and drop
2922
+ * node.draggable(false);
2923
+ */
1581
2924
  addGetterSetter(Node, 'draggable', false, getBooleanValidator());
1582
2925
  Factory.backCompat(Node, {
1583
2926
  rotateDeg: 'rotate',