konva 10.4.0 → 10.6.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 (63) hide show
  1. package/README.md +4 -4
  2. package/konva.js +3432 -3746
  3. package/konva.min.js +4 -4
  4. package/lib/Animation.d.ts +2 -2
  5. package/lib/Animation.js +2 -2
  6. package/lib/BezierFunctions.d.ts +1 -1
  7. package/lib/BezierFunctions.js +76 -116
  8. package/lib/Canvas.d.ts +1 -1
  9. package/lib/Canvas.js +8 -5
  10. package/lib/Container.js +9 -6
  11. package/lib/Context.d.ts +4 -5
  12. package/lib/Context.js +77 -72
  13. package/lib/DragAndDrop.d.ts +5 -3
  14. package/lib/DragAndDrop.js +65 -29
  15. package/lib/Factory.d.ts +3 -2
  16. package/lib/Factory.js +10 -9
  17. package/lib/Global.d.ts +0 -6
  18. package/lib/Global.js +2 -8
  19. package/lib/Layer.js +9 -6
  20. package/lib/Node.d.ts +33 -15
  21. package/lib/Node.js +179 -135
  22. package/lib/PointerEvents.d.ts +1 -2
  23. package/lib/PointerEvents.js +20 -18
  24. package/lib/Shape.d.ts +2 -2
  25. package/lib/Shape.js +51 -7
  26. package/lib/Stage.d.ts +23 -14
  27. package/lib/Stage.js +221 -93
  28. package/lib/Tween.js +59 -66
  29. package/lib/Util.d.ts +3 -2
  30. package/lib/Util.js +43 -16
  31. package/lib/_CoreInternals.d.ts +25 -11
  32. package/lib/_FullInternals.d.ts +25 -11
  33. package/lib/filters/Blur.js +16 -12
  34. package/lib/filters/Brighten.d.ts +1 -0
  35. package/lib/filters/Brighten.js +1 -0
  36. package/lib/filters/Brightness.d.ts +2 -1
  37. package/lib/filters/Brightness.js +4 -4
  38. package/lib/filters/Emboss.js +16 -58
  39. package/lib/filters/Kaleidoscope.js +8 -15
  40. package/lib/filters/Mask.js +8 -8
  41. package/lib/filters/Pixelate.js +16 -29
  42. package/lib/filters/Threshold.d.ts +1 -1
  43. package/lib/filters/Threshold.js +1 -1
  44. package/lib/shapes/Arc.js +5 -3
  45. package/lib/shapes/Arrow.d.ts +2 -6
  46. package/lib/shapes/Arrow.js +68 -46
  47. package/lib/shapes/Image.js +16 -19
  48. package/lib/shapes/Label.d.ts +2 -3
  49. package/lib/shapes/Label.js +7 -21
  50. package/lib/shapes/Line.d.ts +1 -1
  51. package/lib/shapes/Line.js +1 -1
  52. package/lib/shapes/Path.d.ts +27 -2
  53. package/lib/shapes/Path.js +148 -142
  54. package/lib/shapes/RegularPolygon.js +1 -1
  55. package/lib/shapes/Sprite.js +2 -6
  56. package/lib/shapes/Text.d.ts +12 -4
  57. package/lib/shapes/Text.js +96 -54
  58. package/lib/shapes/TextPath.d.ts +4 -3
  59. package/lib/shapes/TextPath.js +40 -26
  60. package/lib/shapes/Transformer.d.ts +16 -1
  61. package/lib/shapes/Transformer.js +209 -130
  62. package/lib/types.d.ts +2 -2
  63. package/package.json +4 -3
package/lib/Node.js CHANGED
@@ -6,82 +6,75 @@ import { Factory } from "./Factory.js";
6
6
  import { Konva } from "./Global.js";
7
7
  import { Transform, Util } from "./Util.js";
8
8
  import { getBooleanValidator, getNumberValidator, getStringValidator, } from "./Validators.js";
9
- // CSS filter parser for fallback to function filters
9
+ // CSS filter parser for fallback to function filters.
10
10
  function parseCSSFilters(cssFilter) {
11
- // Parse common CSS filter functions and map to Konva filters
12
- const filterRegex = /(\w+)\(([^)]+)\)/g;
11
+ const steps = [];
12
+ const filterRegex = /(\w+)\(([^)]*)\)/g;
13
13
  let match;
14
14
  while ((match = filterRegex.exec(cssFilter)) !== null) {
15
- const [, filterName, filterValue] = match;
16
- switch (filterName) {
17
- case 'blur': {
18
- const blurRadius = parseFloat(filterValue.replace('px', ''));
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
22
- this.blurRadius(blurRadius * 0.5);
23
- // Access filters through dynamic import to avoid circular dependency
24
- const KonvaFilters = Konva.Filters;
25
- if (KonvaFilters && KonvaFilters.Blur) {
26
- KonvaFilters.Blur.call(this, imageData);
27
- }
28
- };
29
- }
30
- case 'brightness': {
31
- const brightness = filterValue.includes('%')
32
- ? parseFloat(filterValue) / 100
33
- : parseFloat(filterValue);
34
- return function (imageData) {
35
- this.brightness(brightness); // CSS uses multiplier
36
- const KonvaFilters = Konva.Filters;
37
- if (KonvaFilters && KonvaFilters.Brightness) {
38
- KonvaFilters.Brightness.call(this, imageData);
39
- }
40
- };
41
- }
42
- case 'contrast': {
43
- const contrast = parseFloat(filterValue);
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)
47
- const konvaContrast = 100 * (Math.sqrt(contrast) - 1);
48
- this.contrast(konvaContrast);
49
- const KonvaFilters = Konva.Filters;
50
- if (KonvaFilters && KonvaFilters.Contrast) {
51
- KonvaFilters.Contrast.call(this, imageData);
15
+ const [, name, argument] = match;
16
+ if (![
17
+ 'blur',
18
+ 'brightness',
19
+ 'contrast',
20
+ 'grayscale',
21
+ 'sepia',
22
+ 'invert',
23
+ ].includes(name)) {
24
+ Util.warn(`CSS filter "${name}" is not supported in fallback mode. Consider using function filters for better compatibility.`);
25
+ continue;
26
+ }
27
+ const value = argument.trim() === ''
28
+ ? name === 'blur'
29
+ ? 0
30
+ : 1
31
+ : parseFloat(argument) / (argument.includes('%') ? 100 : 1);
32
+ steps.push({ name, value });
33
+ }
34
+ return function (imageData, pixelRatio = 1) {
35
+ var _a;
36
+ for (const { name, value } of steps) {
37
+ if (['grayscale', 'sepia', 'invert'].includes(name)) {
38
+ const amount = Math.min(1, Math.max(0, value));
39
+ const data = imageData.data;
40
+ for (let i = 0; i < data.length; i += 4) {
41
+ const r = data[i], g = data[i + 1], b = data[i + 2];
42
+ let red, green, blue;
43
+ if (name === 'grayscale') {
44
+ red = green = blue = 0.2126 * r + 0.7152 * g + 0.0722 * b;
52
45
  }
53
- };
54
- }
55
- case 'grayscale': {
56
- return function (imageData) {
57
- const KonvaFilters = Konva.Filters;
58
- if (KonvaFilters && KonvaFilters.Grayscale) {
59
- KonvaFilters.Grayscale.call(this, imageData);
46
+ else if (name === 'sepia') {
47
+ red = 0.393 * r + 0.769 * g + 0.189 * b;
48
+ green = 0.349 * r + 0.686 * g + 0.168 * b;
49
+ blue = 0.272 * r + 0.534 * g + 0.131 * b;
60
50
  }
61
- };
62
- }
63
- case 'sepia': {
64
- return function (imageData) {
65
- const KonvaFilters = Konva.Filters;
66
- if (KonvaFilters && KonvaFilters.Sepia) {
67
- KonvaFilters.Sepia.call(this, imageData);
51
+ else {
52
+ red = 255 - r;
53
+ green = 255 - g;
54
+ blue = 255 - b;
68
55
  }
69
- };
70
- }
71
- case 'invert': {
72
- return function (imageData) {
73
- const KonvaFilters = Konva.Filters;
74
- if (KonvaFilters && KonvaFilters.Invert) {
75
- KonvaFilters.Invert.call(this, imageData);
76
- }
77
- };
56
+ // CSS interpolates the color matrix before clamping the result.
57
+ data[i] = r + (red - r) * amount;
58
+ data[i + 1] = g + (green - g) * amount;
59
+ data[i + 2] = b + (blue - b) * amount;
60
+ }
61
+ continue;
78
62
  }
79
- default:
80
- Util.warn(`CSS filter "${filterName}" is not supported in fallback mode. Consider using function filters for better compatibility.`);
81
- break;
82
- }
83
- }
84
- return () => { };
63
+ const filter = (_a = Konva.Filters) === null || _a === void 0 ? void 0 : _a[Util._capitalize(name)];
64
+ if (!filter)
65
+ continue;
66
+ // Supply filter parameters without setters or changes to the node.
67
+ const context = Object.create(this);
68
+ context.attrs = { ...this.attrs };
69
+ if (name === 'blur')
70
+ context.attrs.blurRadius = value * 0.5;
71
+ if (name === 'brightness')
72
+ context.attrs.brightness = value;
73
+ if (name === 'contrast')
74
+ context.attrs.contrast = 100 * (Math.sqrt(value) - 1);
75
+ filter.call(context, imageData, pixelRatio);
76
+ }
77
+ };
85
78
  }
86
79
  // CONSTANTS
87
80
  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 = [
@@ -104,14 +97,6 @@ const ABSOLUTE_OPACITY = 'absoluteOpacity', ABSOLUTE_TRANSFORM = 'absoluteTransf
104
97
  'transformsEnabledChange.konva',
105
98
  ].join(SPACE);
106
99
  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
100
  // "perfect drawing" buffer for cache() and toCanvas(): it mirrors the target
116
101
  // canvas and is drawn back at (x, y) in the target's coordinate space.
117
102
  // It starts empty and Shape.drawScene sizes it on first use, so nodes
@@ -126,6 +111,14 @@ function createBufferCanvas(target, x, y) {
126
111
  bufferCanvas.y = y;
127
112
  return bufferCanvas;
128
113
  }
114
+ /**
115
+ * Node constructor. Nodes are entities that can be transformed, layered,
116
+ * and have bound events. The stage, layers, groups, and shapes all extend Node.
117
+ * @constructor
118
+ * @memberof Konva
119
+ * @param {Object} config
120
+ * @@nodeParams
121
+ */
129
122
  export class Node {
130
123
  constructor(config) {
131
124
  this._id = idCounter++;
@@ -166,6 +159,10 @@ export class Node {
166
159
  }
167
160
  else {
168
161
  this._cache = {};
162
+ // clearCache() also reaches descendants whose ancestor transform changes
163
+ // were suppressed while cached. Invalidate their saved Transformer bounds.
164
+ if (this._attrsVersion !== undefined)
165
+ this._attrsVersion++;
169
166
  }
170
167
  }
171
168
  // drop the cached canvases and give their memory back
@@ -199,7 +196,7 @@ export class Node {
199
196
  _clearSelfAndDescendantCache(attr) {
200
197
  this._clearCache(attr);
201
198
  // trigger clear cache, so transformer can use it
202
- if (attr === ABSOLUTE_TRANSFORM) {
199
+ if (attr === undefined || attr === ABSOLUTE_TRANSFORM) {
203
200
  this.fire('absoluteTransformChange');
204
201
  }
205
202
  }
@@ -278,23 +275,23 @@ export class Node {
278
275
  conf.y === undefined ||
279
276
  conf.width === undefined ||
280
277
  conf.height === undefined) {
278
+ const wasUnderCache = this._isUnderCache;
279
+ this._isUnderCache = true;
281
280
  rect = this.getClientRect({
282
281
  skipTransform: true,
283
282
  relativeTo: this.getParent() || undefined,
284
283
  });
284
+ this._isUnderCache = wasUnderCache;
285
285
  }
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;
287
- if (!width || !height || !isFinite(x + y + width + height)) {
286
+ let x = conf.x === undefined ? Math.floor(rect.x) : conf.x, y = conf.y === undefined ? Math.floor(rect.y) : conf.y,
287
+ // round the far edge, not the size, so the last row and column fit in
288
+ width = Math.ceil(conf.width || rect.x + rect.width - x), height = Math.ceil(conf.height || rect.y + rect.height - y), pixelRatio = conf.pixelRatio, offset = conf.offset || 0, drawBorder = conf.drawBorder || false, hitCanvasPixelRatio = conf.hitCanvasPixelRatio || 1;
289
+ if (width <= 0 || height <= 0 || !isFinite(x + y + width + height)) {
288
290
  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
291
  return this;
290
292
  }
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
294
- const extraPaddingX = Math.abs(Math.round(rect.x) - x) > 0.5 ? 1 : 0;
295
- const extraPaddingY = Math.abs(Math.round(rect.y) - y) > 0.5 ? 1 : 0;
296
- width += offset * 2 + extraPaddingX;
297
- height += offset * 2 + extraPaddingY;
293
+ width += offset * 2;
294
+ height += offset * 2;
298
295
  x -= offset;
299
296
  y -= offset;
300
297
  const cachedSceneCanvas = new SceneCanvas({
@@ -360,6 +357,8 @@ export class Node {
360
357
  x: x,
361
358
  y: y,
362
359
  };
360
+ // Entering cache space changes non-scaling stroke bounds for descendants.
361
+ this._clearSelfAndDescendantCache();
363
362
  this._requestDraw();
364
363
  return this;
365
364
  }
@@ -402,6 +401,8 @@ export class Node {
402
401
  /**
403
402
  * Return client rectangle {x, y, width, height} of node. This rectangle also include all styling (strokes, shadows, etc).
404
403
  * The purpose of the method is similar to getBoundingClientRect API of the DOM.
404
+ * Non-scaling stroke padding is converted from its drawing canvas to the requested coordinates.
405
+ * Cached strokes use the cache's coordinates; their pixels scale with the cached bitmap.
405
406
  * @method
406
407
  * @name Konva.Node#getClientRect
407
408
  * @param {Object} config
@@ -499,7 +500,11 @@ export class Node {
499
500
  const ratio = sceneCanvas.pixelRatio;
500
501
  filterCanvas.setSizeIfChanged(sceneCanvas._logicalWidth, sceneCanvas._logicalHeight);
501
502
  if (useNativeOnly) {
502
- const finalFilter = filters.join(' ');
503
+ // Canvas filters use backing-pixel coordinates, independent of the CTM.
504
+ // Scale length tokens, leaving colors, percentages and URL references alone.
505
+ const finalFilter = filters
506
+ .join(' ')
507
+ .replace(/url\((?:[^()"']|"[^"]*"|'[^']*')*\)|"[^"]*"|'[^']*'|([-+]?(?:\d*\.)?\d+(?:e[-+]?\d+)?)(px|em|rem|ex|ch|cap|ic|lh|rlh|vw|vh|vmin|vmax|cm|mm|q|in|pt|pc)\b/gi, (token, value, unit) => value === undefined ? token : `${Number(value) * ratio}${unit}`);
503
508
  filterContext.clear();
504
509
  filterContext.save();
505
510
  filterContext.setAttr('filter', finalFilter);
@@ -520,7 +525,7 @@ export class Node {
520
525
  if (typeof filter === 'string') {
521
526
  filter = parseCSSFilters(filter);
522
527
  }
523
- filter.call(this, imageData);
528
+ filter.call(this, imageData, ratio);
524
529
  }
525
530
  filterContext.putImageData(imageData, 0, 0);
526
531
  }
@@ -745,15 +750,15 @@ export class Node {
745
750
  this._clearSelfAndDescendantCache(LISTENING);
746
751
  }
747
752
  _remove() {
748
- // every cached attr that is calculated via node tree
749
- // traversal must be cleared when removing a node
750
- this._clearCaches();
751
753
  const parent = this.getParent();
752
754
  if (parent && parent.children) {
753
755
  parent.children.splice(this.index, 1);
754
756
  parent._setChildrenIndices();
755
757
  this.parent = null;
756
758
  }
759
+ // every cached attr that is calculated via node tree
760
+ // traversal must be cleared when removing a node
761
+ this._clearCaches();
757
762
  }
758
763
  /**
759
764
  * remove and destroy a node. Kill it and delete forever! You should not reuse node after destroy().
@@ -997,6 +1002,10 @@ export class Node {
997
1002
  // for performance reasons, lets batch transform reset
998
1003
  // so it work faster
999
1004
  _batchTransformChanges(func) {
1005
+ if (this._batchingTransformChange) {
1006
+ func();
1007
+ return;
1008
+ }
1000
1009
  this._batchingTransformChange = true;
1001
1010
  try {
1002
1011
  func();
@@ -1304,7 +1313,8 @@ export class Node {
1304
1313
  */
1305
1314
  toObject() {
1306
1315
  var _a;
1307
- let attrs = this.getAttrs(), key, val, getter, defaultValue, nonPlainObject;
1316
+ const attrs = this.getAttrs();
1317
+ let key, val, nonPlainObject;
1308
1318
  const obj = {
1309
1319
  attrs: {},
1310
1320
  className: this.getClassName(),
@@ -1318,18 +1328,18 @@ export class Node {
1318
1328
  if (nonPlainObject) {
1319
1329
  continue;
1320
1330
  }
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
1325
- delete attrs[key];
1326
- defaultValue = getter ? getter.call(this) : null;
1327
- // restore attr value
1328
- attrs[key] = val;
1329
- if (defaultValue !== val) {
1330
- obj.attrs[key] = Util.isObject(val)
1331
- ? Util._prepareToStringify(val)
1332
- : val;
1331
+ // only the getters generated by Factory carry a default, so an explicit
1332
+ // value equal to a computed one (Text width, dragDistance) is kept
1333
+ // Shared filter parameters can distinguish an explicit value from unset.
1334
+ if (((_a = this['get' + Util._capitalize(key)]) === null || _a === void 0 ? void 0 : _a._def) !== val ||
1335
+ key === 'brightness' ||
1336
+ key === 'threshold') {
1337
+ obj.attrs[key] =
1338
+ key === 'filters' && Util._isArray(val)
1339
+ ? val.filter((filter) => typeof filter === 'string')
1340
+ : Util.isObject(val)
1341
+ ? Util._prepareToStringify(val)
1342
+ : val;
1333
1343
  }
1334
1344
  }
1335
1345
  return obj;
@@ -1703,9 +1713,11 @@ export class Node {
1703
1713
  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
1714
  }
1705
1715
  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({
1706
- width: config.width || Math.ceil(box.width) || (stage ? stage.width() : 0),
1716
+ width: config.width ||
1717
+ Math.max(0, Math.ceil(box.x + box.width - x)) ||
1718
+ (stage ? stage.width() : 0),
1707
1719
  height: config.height ||
1708
- Math.ceil(box.height) ||
1720
+ Math.max(0, Math.ceil(box.y + box.height - y)) ||
1709
1721
  (stage ? stage.height() : 0),
1710
1722
  pixelRatio: pixelRatio,
1711
1723
  }), context = canvas.getContext();
@@ -1734,8 +1746,9 @@ export class Node {
1734
1746
  * @param {Number} [config.width] width of canvas section
1735
1747
  * @param {Number} [config.height] height of canvas section
1736
1748
  * @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.
1749
+ * Higher pixel ratios increase export resolution. Cached nodes keep their cache resolution.
1750
+ * Rebuild caches at the export pixel ratio to preserve detail.
1751
+ * The pixel ratio multiplies the dimensions of the exported image.
1739
1752
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1740
1753
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1741
1754
  * @example
@@ -1761,15 +1774,17 @@ export class Node {
1761
1774
  * you can specify the quality from 0 to 1, where 0 is very poor quality and 1
1762
1775
  * is very high quality
1763
1776
  * @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.
1777
+ * Higher pixel ratios increase export resolution. Cached nodes keep their cache resolution.
1778
+ * Rebuild caches at the export pixel ratio to preserve detail.
1779
+ * The pixel ratio multiplies the dimensions of the exported image.
1766
1780
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1767
1781
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1768
1782
  * @returns {String}
1769
1783
  */
1770
1784
  toDataURL(config) {
1785
+ var _a;
1771
1786
  config = config || {};
1772
- const mimeType = config.mimeType || null, quality = config.quality || null;
1787
+ const mimeType = config.mimeType || null, quality = (_a = config.quality) !== null && _a !== void 0 ? _a : null;
1773
1788
  const url = this._toKonvaCanvas(config).toDataURL(mimeType, quality);
1774
1789
  if (config.callback) {
1775
1790
  config.callback(url);
@@ -1795,8 +1810,9 @@ export class Node {
1795
1810
  * you can specify the quality from 0 to 1, where 0 is very poor quality and 1
1796
1811
  * is very high quality
1797
1812
  * @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.
1813
+ * Higher pixel ratios increase export resolution. Cached nodes keep their cache resolution.
1814
+ * Rebuild caches at the export pixel ratio to preserve detail.
1815
+ * The pixel ratio multiplies the dimensions of the exported image.
1800
1816
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1801
1817
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1802
1818
  * @return {Promise<Image>}
@@ -1810,13 +1826,11 @@ export class Node {
1810
1826
  toImage(config) {
1811
1827
  return new Promise((resolve, reject) => {
1812
1828
  try {
1813
- const callback = config === null || config === void 0 ? void 0 : config.callback;
1814
- if (callback)
1815
- delete config.callback;
1816
- Util._urlToImage(this.toDataURL(config), function (img) {
1829
+ const { callback, ...rest } = config || {};
1830
+ Util._urlToImage(this.toDataURL(rest), function (img) {
1817
1831
  resolve(img);
1818
1832
  callback === null || callback === void 0 ? void 0 : callback(img);
1819
- });
1833
+ }, reject);
1820
1834
  }
1821
1835
  catch (err) {
1822
1836
  reject(err);
@@ -1836,23 +1850,27 @@ export class Node {
1836
1850
  * @param {Number} [config.width] width of canvas section
1837
1851
  * @param {Number} [config.height] height of canvas section
1838
1852
  * @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.
1853
+ * Higher pixel ratios increase export resolution. Cached nodes keep their cache resolution.
1854
+ * Rebuild caches at the export pixel ratio to preserve detail.
1855
+ * The pixel ratio multiplies the dimensions of the exported image.
1841
1856
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1842
1857
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1843
1858
  * @example
1844
1859
  * var blob = await node.toBlob({});
1845
- * @returns {Promise<Blob>}
1860
+ * @returns {Promise<Blob>} rejects if the canvas can not be encoded
1846
1861
  */
1847
1862
  toBlob(config) {
1848
1863
  return new Promise((resolve, reject) => {
1849
1864
  try {
1850
- const callback = config === null || config === void 0 ? void 0 : config.callback;
1851
- if (callback)
1852
- delete config.callback;
1853
1865
  this.toCanvas(config).toBlob((blob) => {
1866
+ var _a;
1867
+ // the canvas reports a failed encode by passing null
1868
+ if (!blob) {
1869
+ reject(new Error('Konva: toBlob() failed, the canvas was not encoded'));
1870
+ return;
1871
+ }
1854
1872
  resolve(blob);
1855
- callback === null || callback === void 0 ? void 0 : callback(blob);
1873
+ (_a = config === null || config === void 0 ? void 0 : config.callback) === null || _a === void 0 ? void 0 : _a.call(config, blob);
1856
1874
  }, config === null || config === void 0 ? void 0 : config.mimeType, config === null || config === void 0 ? void 0 : config.quality);
1857
1875
  }
1858
1876
  catch (err) {
@@ -2030,6 +2048,8 @@ export class Node {
2030
2048
  else {
2031
2049
  this.attrs[key] = val;
2032
2050
  }
2051
+ if (this._attrsVersion !== undefined)
2052
+ this._attrsVersion++;
2033
2053
  if (this._shouldFireChangeEvents) {
2034
2054
  this._fireChangeEvent(key, oldVal, val);
2035
2055
  }
@@ -2143,6 +2163,7 @@ export class Node {
2143
2163
  }
2144
2164
  // drag & drop
2145
2165
  _createDragElement(evt) {
2166
+ var _a;
2146
2167
  const pointerId = evt ? evt.pointerId : undefined;
2147
2168
  const stage = this.getStage();
2148
2169
  const ap = this.getAbsolutePosition();
@@ -2152,6 +2173,12 @@ export class Node {
2152
2173
  const pos = stage._getPointerById(pointerId) ||
2153
2174
  stage._changedPointerPositions[0] ||
2154
2175
  ap;
2176
+ const type = ((_a = evt === null || evt === void 0 ? void 0 : evt.evt) === null || _a === void 0 ? void 0 : _a.type)
2177
+ ? Util._getEventType(evt.evt.type)
2178
+ : stage._pointerEventType;
2179
+ // drags follow mouse and touch window events only, so a drag started from
2180
+ // a pointer event stays unbound until such an event attaches its pointer
2181
+ const bound = type !== 'pointer';
2155
2182
  DD._dragElements.set(this._id, {
2156
2183
  node: this,
2157
2184
  startPointerPos: pos,
@@ -2160,7 +2187,10 @@ export class Node {
2160
2187
  y: pos.y - ap.y,
2161
2188
  },
2162
2189
  dragStatus: 'ready',
2163
- pointerId,
2190
+ pointerId: bound
2191
+ ? (pointerId !== null && pointerId !== void 0 ? pointerId : ('id' in pos ? pos.id : undefined))
2192
+ : undefined,
2193
+ pointerEventType: bound ? type : undefined,
2164
2194
  startEvent: evt,
2165
2195
  });
2166
2196
  }
@@ -2170,6 +2200,7 @@ export class Node {
2170
2200
  * @name Konva.Node#startDrag
2171
2201
  */
2172
2202
  startDrag(evt, bubbleEvent = true) {
2203
+ var _a;
2173
2204
  if (!DD._dragElements.has(this._id)) {
2174
2205
  this._createDragElement(evt);
2175
2206
  }
@@ -2179,6 +2210,7 @@ export class Node {
2179
2210
  return;
2180
2211
  }
2181
2212
  elem.dragStatus = 'dragging';
2213
+ (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._cancelClick(elem.pointerId, elem.pointerEventType);
2182
2214
  this.fire('dragstart', {
2183
2215
  type: 'dragstart',
2184
2216
  target: this,
@@ -2224,11 +2256,12 @@ export class Node {
2224
2256
  */
2225
2257
  stopDrag(evt) {
2226
2258
  const elem = DD._dragElements.get(this._id);
2227
- if (elem) {
2228
- elem.dragStatus = 'stopped';
2259
+ if (!elem) {
2260
+ return;
2229
2261
  }
2230
- DD._endDragBefore(evt);
2231
- DD._endDragAfter(evt);
2262
+ elem.dragStatus = 'stopped';
2263
+ DD._endDragBefore(evt, undefined, elem);
2264
+ DD._endDragAfter(evt, elem);
2232
2265
  }
2233
2266
  setDraggable(draggable) {
2234
2267
  this._setAttr('draggable', draggable);
@@ -2251,7 +2284,7 @@ export class Node {
2251
2284
  if (!canDrag) {
2252
2285
  return;
2253
2286
  }
2254
- if (this.isDragging()) {
2287
+ if (DD._dragElements.has(this._id)) {
2255
2288
  return;
2256
2289
  }
2257
2290
  let hasDraggingChild = false;
@@ -2353,10 +2386,11 @@ export class Node {
2353
2386
  obj.attrs.container = container;
2354
2387
  }
2355
2388
  if (!Konva[className]) {
2389
+ const fallback = children ? 'Group' : 'Shape';
2356
2390
  Util.warn('Can not find a node with class name "' +
2357
2391
  className +
2358
- '". Fallback to "Shape".');
2359
- className = 'Shape';
2392
+ `". Fallback to "${fallback}".`);
2393
+ className = fallback;
2360
2394
  }
2361
2395
  const Class = Konva[className];
2362
2396
  no = new Class(obj.attrs);
@@ -2395,6 +2429,13 @@ Node.prototype.on('visibleChange.konva', function () {
2395
2429
  });
2396
2430
  Node.prototype.on('listeningChange.konva', function () {
2397
2431
  this._clearSelfAndDescendantCache(LISTENING);
2432
+ for (let parent = this.getParent(); parent; parent = parent.getParent()) {
2433
+ const cache = parent._getCanvasCache();
2434
+ if (cache === null || cache === void 0 ? void 0 : cache.hit) {
2435
+ Util.releaseCanvas(cache.hit._canvas);
2436
+ cache.hit = null;
2437
+ }
2438
+ }
2398
2439
  });
2399
2440
  Node.prototype.on('opacityChange.konva', function () {
2400
2441
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
@@ -2791,6 +2832,8 @@ addGetterSetter(Node, 'filters', undefined, function (val) {
2791
2832
  * get/set filters. Supports function filters, CSS filter strings, or mixed arrays.
2792
2833
  * CSS filters are applied using native browser performance when possible, function filters use ImageData manipulation.
2793
2834
  * CSS filters automatically fall back to function filters in unsupported browsers.
2835
+ * Blur radii, pixelation sizes and CSS lengths use node coordinates, independent of cache pixelRatio.
2836
+ * Custom filters receive (imageData, pixelRatio). ImageData contains full-resolution backing pixels.
2794
2837
  * @name Konva.Node#filters
2795
2838
  * @method
2796
2839
  * @param {Array} filters array of filter functions and/or CSS filter strings
@@ -2799,7 +2842,8 @@ addGetterSetter(Node, 'filters', undefined, function (val) {
2799
2842
  * // get filters
2800
2843
  * var filters = node.filters();
2801
2844
  *
2802
- * // set CSS filters only (no caching required, uses native performance)
2845
+ * // set CSS filters only (caching required, uses native performance)
2846
+ * node.cache();
2803
2847
  * node.filters(['blur(5px)', 'brightness(1.2)', 'contrast(1.5)']);
2804
2848
  *
2805
2849
  * // set function filters only (caching required)
@@ -4,8 +4,7 @@ import type { Stage } from './Stage.ts';
4
4
  export interface KonvaPointerEvent extends KonvaEventObject<PointerEvent> {
5
5
  pointerId: number;
6
6
  }
7
- export declare function getCapturedShape(pointerId: number): Shape<import("./Shape.ts").ShapeConfig> | Stage | undefined;
8
- export declare function createEvent(evt: PointerEvent): KonvaPointerEvent;
7
+ export declare function getCapturedShape(pointerId: number, stage?: Stage): Shape<import("./Shape.ts").ShapeConfig> | Stage | undefined;
9
8
  export declare function hasPointerCapture(pointerId: number, shape: Shape | Stage): boolean;
10
9
  export declare function setPointerCapture(pointerId: number, shape: Shape | Stage): void;
11
10
  export declare function releaseCapturesOf(node: Node): void;