konva 10.5.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 (62) hide show
  1. package/README.md +4 -4
  2. package/konva.js +3247 -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 +4 -3
  14. package/lib/DragAndDrop.js +39 -25
  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 +21 -12
  21. package/lib/Node.js +159 -126
  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 +19 -13
  27. package/lib/Stage.js +182 -86
  28. package/lib/Tween.js +59 -66
  29. package/lib/Util.d.ts +2 -2
  30. package/lib/Util.js +21 -16
  31. package/lib/_CoreInternals.d.ts +23 -11
  32. package/lib/_FullInternals.d.ts +23 -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 +11 -2
  53. package/lib/shapes/Path.js +132 -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.js +88 -91
  61. package/lib/types.d.ts +2 -2
  62. 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);
52
- }
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);
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;
60
45
  }
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);
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;
68
50
  }
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);
51
+ else {
52
+ red = 255 - r;
53
+ green = 255 - g;
54
+ blue = 255 - b;
76
55
  }
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 = [
@@ -203,7 +196,7 @@ export class Node {
203
196
  _clearSelfAndDescendantCache(attr) {
204
197
  this._clearCache(attr);
205
198
  // trigger clear cache, so transformer can use it
206
- if (attr === ABSOLUTE_TRANSFORM) {
199
+ if (attr === undefined || attr === ABSOLUTE_TRANSFORM) {
207
200
  this.fire('absoluteTransformChange');
208
201
  }
209
202
  }
@@ -282,23 +275,23 @@ export class Node {
282
275
  conf.y === undefined ||
283
276
  conf.width === undefined ||
284
277
  conf.height === undefined) {
278
+ const wasUnderCache = this._isUnderCache;
279
+ this._isUnderCache = true;
285
280
  rect = this.getClientRect({
286
281
  skipTransform: true,
287
282
  relativeTo: this.getParent() || undefined,
288
283
  });
284
+ this._isUnderCache = wasUnderCache;
289
285
  }
290
- let width = Math.ceil(conf.width || rect.width), height = Math.ceil(conf.height || rect.height), pixelRatio = conf.pixelRatio, x = conf.x === undefined ? Math.floor(rect.x) : conf.x, y = conf.y === undefined ? Math.floor(rect.y) : conf.y, offset = conf.offset || 0, drawBorder = conf.drawBorder || false, hitCanvasPixelRatio = conf.hitCanvasPixelRatio || 1;
291
- 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)) {
292
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.`);
293
291
  return this;
294
292
  }
295
- // because using Math.floor on x, y position may shift drawing
296
- // to avoid shift we need to increase size
297
- // but we better to avoid it, for better filters flows
298
- const extraPaddingX = Math.abs(Math.round(rect.x) - x) > 0.5 ? 1 : 0;
299
- const extraPaddingY = Math.abs(Math.round(rect.y) - y) > 0.5 ? 1 : 0;
300
- width += offset * 2 + extraPaddingX;
301
- height += offset * 2 + extraPaddingY;
293
+ width += offset * 2;
294
+ height += offset * 2;
302
295
  x -= offset;
303
296
  y -= offset;
304
297
  const cachedSceneCanvas = new SceneCanvas({
@@ -364,6 +357,8 @@ export class Node {
364
357
  x: x,
365
358
  y: y,
366
359
  };
360
+ // Entering cache space changes non-scaling stroke bounds for descendants.
361
+ this._clearSelfAndDescendantCache();
367
362
  this._requestDraw();
368
363
  return this;
369
364
  }
@@ -406,6 +401,8 @@ export class Node {
406
401
  /**
407
402
  * Return client rectangle {x, y, width, height} of node. This rectangle also include all styling (strokes, shadows, etc).
408
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.
409
406
  * @method
410
407
  * @name Konva.Node#getClientRect
411
408
  * @param {Object} config
@@ -503,7 +500,11 @@ export class Node {
503
500
  const ratio = sceneCanvas.pixelRatio;
504
501
  filterCanvas.setSizeIfChanged(sceneCanvas._logicalWidth, sceneCanvas._logicalHeight);
505
502
  if (useNativeOnly) {
506
- 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}`);
507
508
  filterContext.clear();
508
509
  filterContext.save();
509
510
  filterContext.setAttr('filter', finalFilter);
@@ -524,7 +525,7 @@ export class Node {
524
525
  if (typeof filter === 'string') {
525
526
  filter = parseCSSFilters(filter);
526
527
  }
527
- filter.call(this, imageData);
528
+ filter.call(this, imageData, ratio);
528
529
  }
529
530
  filterContext.putImageData(imageData, 0, 0);
530
531
  }
@@ -749,15 +750,15 @@ export class Node {
749
750
  this._clearSelfAndDescendantCache(LISTENING);
750
751
  }
751
752
  _remove() {
752
- // every cached attr that is calculated via node tree
753
- // traversal must be cleared when removing a node
754
- this._clearCaches();
755
753
  const parent = this.getParent();
756
754
  if (parent && parent.children) {
757
755
  parent.children.splice(this.index, 1);
758
756
  parent._setChildrenIndices();
759
757
  this.parent = null;
760
758
  }
759
+ // every cached attr that is calculated via node tree
760
+ // traversal must be cleared when removing a node
761
+ this._clearCaches();
761
762
  }
762
763
  /**
763
764
  * remove and destroy a node. Kill it and delete forever! You should not reuse node after destroy().
@@ -1001,6 +1002,10 @@ export class Node {
1001
1002
  // for performance reasons, lets batch transform reset
1002
1003
  // so it work faster
1003
1004
  _batchTransformChanges(func) {
1005
+ if (this._batchingTransformChange) {
1006
+ func();
1007
+ return;
1008
+ }
1004
1009
  this._batchingTransformChange = true;
1005
1010
  try {
1006
1011
  func();
@@ -1308,7 +1313,8 @@ export class Node {
1308
1313
  */
1309
1314
  toObject() {
1310
1315
  var _a;
1311
- let attrs = this.getAttrs(), key, val, getter, defaultValue, nonPlainObject;
1316
+ const attrs = this.getAttrs();
1317
+ let key, val, nonPlainObject;
1312
1318
  const obj = {
1313
1319
  attrs: {},
1314
1320
  className: this.getClassName(),
@@ -1322,18 +1328,18 @@ export class Node {
1322
1328
  if (nonPlainObject) {
1323
1329
  continue;
1324
1330
  }
1325
- // a custom attribute may share its name with a node method, so only
1326
- // the accessors generated by Factory are asked for the default value
1327
- getter = ((_a = this[key]) === null || _a === void 0 ? void 0 : _a._isAttrAccessor) && this[key];
1328
- // remove attr value so that we can extract the default value from the getter
1329
- delete attrs[key];
1330
- defaultValue = getter ? getter.call(this) : null;
1331
- // restore attr value
1332
- attrs[key] = val;
1333
- if (defaultValue !== val) {
1334
- obj.attrs[key] = Util.isObject(val)
1335
- ? Util._prepareToStringify(val)
1336
- : 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;
1337
1343
  }
1338
1344
  }
1339
1345
  return obj;
@@ -1707,9 +1713,11 @@ export class Node {
1707
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.`);
1708
1714
  }
1709
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({
1710
- 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),
1711
1719
  height: config.height ||
1712
- Math.ceil(box.height) ||
1720
+ Math.max(0, Math.ceil(box.y + box.height - y)) ||
1713
1721
  (stage ? stage.height() : 0),
1714
1722
  pixelRatio: pixelRatio,
1715
1723
  }), context = canvas.getContext();
@@ -1738,8 +1746,9 @@ export class Node {
1738
1746
  * @param {Number} [config.width] width of canvas section
1739
1747
  * @param {Number} [config.height] height of canvas section
1740
1748
  * @param {Number} [config.pixelRatio] pixelRatio of output canvas. Default is 1.
1741
- * You can use that property to increase quality of the image, for example for super hight quality exports
1742
- * or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
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.
1743
1752
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1744
1753
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1745
1754
  * @example
@@ -1765,15 +1774,17 @@ export class Node {
1765
1774
  * you can specify the quality from 0 to 1, where 0 is very poor quality and 1
1766
1775
  * is very high quality
1767
1776
  * @param {Number} [config.pixelRatio] pixelRatio of output image url. Default is 1.
1768
- * You can use that property to increase quality of the image, for example for super hight quality exports
1769
- * or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
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.
1770
1780
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1771
1781
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1772
1782
  * @returns {String}
1773
1783
  */
1774
1784
  toDataURL(config) {
1785
+ var _a;
1775
1786
  config = config || {};
1776
- 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;
1777
1788
  const url = this._toKonvaCanvas(config).toDataURL(mimeType, quality);
1778
1789
  if (config.callback) {
1779
1790
  config.callback(url);
@@ -1799,8 +1810,9 @@ export class Node {
1799
1810
  * you can specify the quality from 0 to 1, where 0 is very poor quality and 1
1800
1811
  * is very high quality
1801
1812
  * @param {Number} [config.pixelRatio] pixelRatio of output image. Default is 1.
1802
- * You can use that property to increase quality of the image, for example for super hight quality exports
1803
- * or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
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.
1804
1816
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1805
1817
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1806
1818
  * @return {Promise<Image>}
@@ -1814,13 +1826,11 @@ export class Node {
1814
1826
  toImage(config) {
1815
1827
  return new Promise((resolve, reject) => {
1816
1828
  try {
1817
- const callback = config === null || config === void 0 ? void 0 : config.callback;
1818
- if (callback)
1819
- delete config.callback;
1820
- Util._urlToImage(this.toDataURL(config), function (img) {
1829
+ const { callback, ...rest } = config || {};
1830
+ Util._urlToImage(this.toDataURL(rest), function (img) {
1821
1831
  resolve(img);
1822
1832
  callback === null || callback === void 0 ? void 0 : callback(img);
1823
- });
1833
+ }, reject);
1824
1834
  }
1825
1835
  catch (err) {
1826
1836
  reject(err);
@@ -1840,8 +1850,9 @@ export class Node {
1840
1850
  * @param {Number} [config.width] width of canvas section
1841
1851
  * @param {Number} [config.height] height of canvas section
1842
1852
  * @param {Number} [config.pixelRatio] pixelRatio of output canvas. Default is 1.
1843
- * You can use that property to increase quality of the image, for example for super hight quality exports
1844
- * or usage on retina (or similar) displays. pixelRatio will be used to multiply the size of exported image.
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.
1845
1856
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1846
1857
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1847
1858
  * @example
@@ -1851,17 +1862,15 @@ export class Node {
1851
1862
  toBlob(config) {
1852
1863
  return new Promise((resolve, reject) => {
1853
1864
  try {
1854
- const callback = config === null || config === void 0 ? void 0 : config.callback;
1855
- if (callback)
1856
- delete config.callback;
1857
1865
  this.toCanvas(config).toBlob((blob) => {
1866
+ var _a;
1858
1867
  // the canvas reports a failed encode by passing null
1859
1868
  if (!blob) {
1860
1869
  reject(new Error('Konva: toBlob() failed, the canvas was not encoded'));
1861
1870
  return;
1862
1871
  }
1863
1872
  resolve(blob);
1864
- 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);
1865
1874
  }, config === null || config === void 0 ? void 0 : config.mimeType, config === null || config === void 0 ? void 0 : config.quality);
1866
1875
  }
1867
1876
  catch (err) {
@@ -2154,6 +2163,7 @@ export class Node {
2154
2163
  }
2155
2164
  // drag & drop
2156
2165
  _createDragElement(evt) {
2166
+ var _a;
2157
2167
  const pointerId = evt ? evt.pointerId : undefined;
2158
2168
  const stage = this.getStage();
2159
2169
  const ap = this.getAbsolutePosition();
@@ -2163,6 +2173,12 @@ export class Node {
2163
2173
  const pos = stage._getPointerById(pointerId) ||
2164
2174
  stage._changedPointerPositions[0] ||
2165
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';
2166
2182
  DD._dragElements.set(this._id, {
2167
2183
  node: this,
2168
2184
  startPointerPos: pos,
@@ -2171,7 +2187,10 @@ export class Node {
2171
2187
  y: pos.y - ap.y,
2172
2188
  },
2173
2189
  dragStatus: 'ready',
2174
- pointerId,
2190
+ pointerId: bound
2191
+ ? (pointerId !== null && pointerId !== void 0 ? pointerId : ('id' in pos ? pos.id : undefined))
2192
+ : undefined,
2193
+ pointerEventType: bound ? type : undefined,
2175
2194
  startEvent: evt,
2176
2195
  });
2177
2196
  }
@@ -2181,6 +2200,7 @@ export class Node {
2181
2200
  * @name Konva.Node#startDrag
2182
2201
  */
2183
2202
  startDrag(evt, bubbleEvent = true) {
2203
+ var _a;
2184
2204
  if (!DD._dragElements.has(this._id)) {
2185
2205
  this._createDragElement(evt);
2186
2206
  }
@@ -2190,6 +2210,7 @@ export class Node {
2190
2210
  return;
2191
2211
  }
2192
2212
  elem.dragStatus = 'dragging';
2213
+ (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._cancelClick(elem.pointerId, elem.pointerEventType);
2193
2214
  this.fire('dragstart', {
2194
2215
  type: 'dragstart',
2195
2216
  target: this,
@@ -2235,11 +2256,12 @@ export class Node {
2235
2256
  */
2236
2257
  stopDrag(evt) {
2237
2258
  const elem = DD._dragElements.get(this._id);
2238
- if (elem) {
2239
- elem.dragStatus = 'stopped';
2259
+ if (!elem) {
2260
+ return;
2240
2261
  }
2241
- DD._endDragBefore(evt);
2242
- DD._endDragAfter(evt);
2262
+ elem.dragStatus = 'stopped';
2263
+ DD._endDragBefore(evt, undefined, elem);
2264
+ DD._endDragAfter(evt, elem);
2243
2265
  }
2244
2266
  setDraggable(draggable) {
2245
2267
  this._setAttr('draggable', draggable);
@@ -2262,7 +2284,7 @@ export class Node {
2262
2284
  if (!canDrag) {
2263
2285
  return;
2264
2286
  }
2265
- if (this.isDragging()) {
2287
+ if (DD._dragElements.has(this._id)) {
2266
2288
  return;
2267
2289
  }
2268
2290
  let hasDraggingChild = false;
@@ -2364,10 +2386,11 @@ export class Node {
2364
2386
  obj.attrs.container = container;
2365
2387
  }
2366
2388
  if (!Konva[className]) {
2389
+ const fallback = children ? 'Group' : 'Shape';
2367
2390
  Util.warn('Can not find a node with class name "' +
2368
2391
  className +
2369
- '". Fallback to "Shape".');
2370
- className = 'Shape';
2392
+ `". Fallback to "${fallback}".`);
2393
+ className = fallback;
2371
2394
  }
2372
2395
  const Class = Konva[className];
2373
2396
  no = new Class(obj.attrs);
@@ -2406,6 +2429,13 @@ Node.prototype.on('visibleChange.konva', function () {
2406
2429
  });
2407
2430
  Node.prototype.on('listeningChange.konva', function () {
2408
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
+ }
2409
2439
  });
2410
2440
  Node.prototype.on('opacityChange.konva', function () {
2411
2441
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
@@ -2802,6 +2832,8 @@ addGetterSetter(Node, 'filters', undefined, function (val) {
2802
2832
  * get/set filters. Supports function filters, CSS filter strings, or mixed arrays.
2803
2833
  * CSS filters are applied using native browser performance when possible, function filters use ImageData manipulation.
2804
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.
2805
2837
  * @name Konva.Node#filters
2806
2838
  * @method
2807
2839
  * @param {Array} filters array of filter functions and/or CSS filter strings
@@ -2810,7 +2842,8 @@ addGetterSetter(Node, 'filters', undefined, function (val) {
2810
2842
  * // get filters
2811
2843
  * var filters = node.filters();
2812
2844
  *
2813
- * // set CSS filters only (no caching required, uses native performance)
2845
+ * // set CSS filters only (caching required, uses native performance)
2846
+ * node.cache();
2814
2847
  * node.filters(['blur(5px)', 'brightness(1.2)', 'contrast(1.5)']);
2815
2848
  *
2816
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;
@@ -3,17 +3,18 @@ const Captures = new Map();
3
3
  // we may use this module for capturing touch events too
4
4
  // so make sure we don't do something super specific to pointer
5
5
  const SUPPORT_POINTER_EVENTS = Konva._global['PointerEvent'] !== undefined;
6
- export function getCapturedShape(pointerId) {
7
- return Captures.get(pointerId);
6
+ export function getCapturedShape(pointerId, stage) {
7
+ const capture = Captures.get(pointerId);
8
+ return capture && (!stage || capture.stage === stage)
9
+ ? capture.shape
10
+ : undefined;
8
11
  }
9
- export function createEvent(evt) {
10
- return {
11
- evt,
12
- pointerId: evt.pointerId,
13
- };
12
+ function fireCapture(shape, type, pointerId) {
13
+ shape._fire(type, { evt: new PointerEvent(type, { pointerId }), pointerId });
14
14
  }
15
15
  export function hasPointerCapture(pointerId, shape) {
16
- return Captures.get(pointerId) === shape;
16
+ var _a;
17
+ return ((_a = Captures.get(pointerId)) === null || _a === void 0 ? void 0 : _a.shape) === shape;
17
18
  }
18
19
  export function setPointerCapture(pointerId, shape) {
19
20
  var _a;
@@ -21,7 +22,8 @@ export function setPointerCapture(pointerId, shape) {
21
22
  const stage = shape.getStage();
22
23
  if (!stage)
23
24
  return;
24
- Captures.set(pointerId, shape);
25
+ // Native capture belongs to this stage even if the shape is reparented.
26
+ Captures.set(pointerId, { shape, stage });
25
27
  if (SUPPORT_POINTER_EVENTS) {
26
28
  // capture on the DOM level too, so the stage keeps receiving the events
27
29
  // of that pointer even when it moves outside of the stage container
@@ -34,32 +36,32 @@ export function setPointerCapture(pointerId, shape) {
34
36
  // ids of mouse and touch events (999 and touch identifiers) and
35
37
  // programmatic calls outside of a pointer event land here
36
38
  }
37
- shape._fire('gotpointercapture', createEvent(new PointerEvent('gotpointercapture')));
39
+ fireCapture(shape, 'gotpointercapture', pointerId);
38
40
  }
39
41
  }
40
- // a destroyed node must not keep receiving the events of its pointer
42
+ // Destroying either the captured node or its native stage ends capture.
41
43
  export function releaseCapturesOf(node) {
42
- Captures.forEach((shape, pointerId) => {
43
- if (shape === node) {
44
+ Captures.forEach(({ shape, stage }, pointerId) => {
45
+ if (shape === node || stage === node) {
44
46
  releaseCapture(pointerId);
45
47
  }
46
48
  });
47
49
  }
48
50
  export function releaseCapture(pointerId, target) {
49
51
  var _a;
50
- const shape = Captures.get(pointerId);
52
+ const capture = Captures.get(pointerId);
51
53
  // a node can only release its own capture
52
- if (!shape || (target && shape !== target))
54
+ if (!capture || (target && capture.shape !== target))
53
55
  return;
54
- const stage = shape.getStage();
56
+ const { shape, stage } = capture;
55
57
  Captures.delete(pointerId);
56
58
  if (SUPPORT_POINTER_EVENTS) {
57
59
  try {
58
- (_a = stage === null || stage === void 0 ? void 0 : stage.content) === null || _a === void 0 ? void 0 : _a.releasePointerCapture(pointerId);
60
+ (_a = stage.content) === null || _a === void 0 ? void 0 : _a.releasePointerCapture(pointerId);
59
61
  }
60
62
  catch (e) {
61
63
  // same as in setPointerCapture: the pointer may not be active
62
64
  }
63
- shape._fire('lostpointercapture', createEvent(new PointerEvent('lostpointercapture')));
65
+ fireCapture(shape, 'lostpointercapture', pointerId);
64
66
  }
65
67
  }
package/lib/Shape.d.ts CHANGED
@@ -191,10 +191,10 @@ export declare class Shape<Config extends ShapeConfig = ShapeConfig> extends Nod
191
191
  height: number;
192
192
  };
193
193
  getClientRect(config?: ShapeGetClientRectConfig): {
194
- width: number;
195
- height: number;
196
194
  x: number;
197
195
  y: number;
196
+ width: number;
197
+ height: number;
198
198
  };
199
199
  drawScene(can?: SceneCanvas, top?: Node, bufferCanvas?: SceneCanvas): this;
200
200
  drawHit(can?: HitCanvas, top?: Node): this;