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