konva 10.5.0 → 10.7.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 (79) hide show
  1. package/README.md +16 -12
  2. package/konva.js +3623 -3819
  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 +10 -3
  9. package/lib/Canvas.js +91 -10
  10. package/lib/Container.d.ts +3 -2
  11. package/lib/Container.js +31 -17
  12. package/lib/Context.d.ts +9 -7
  13. package/lib/Context.js +99 -73
  14. package/lib/DragAndDrop.d.ts +4 -3
  15. package/lib/DragAndDrop.js +39 -25
  16. package/lib/Factory.d.ts +3 -2
  17. package/lib/Factory.js +10 -9
  18. package/lib/Global.d.ts +2 -7
  19. package/lib/Global.js +8 -9
  20. package/lib/Group.d.ts +7 -1
  21. package/lib/Group.js +61 -0
  22. package/lib/Layer.d.ts +1 -1
  23. package/lib/Layer.js +13 -8
  24. package/lib/Node.d.ts +25 -19
  25. package/lib/Node.js +178 -169
  26. package/lib/PointerEvents.d.ts +1 -2
  27. package/lib/PointerEvents.js +20 -18
  28. package/lib/Shape.d.ts +9 -15
  29. package/lib/Shape.js +190 -86
  30. package/lib/Stage.d.ts +19 -15
  31. package/lib/Stage.js +184 -99
  32. package/lib/Tween.js +59 -66
  33. package/lib/Util.d.ts +3 -2
  34. package/lib/Util.js +46 -16
  35. package/lib/_CoreInternals.d.ts +23 -11
  36. package/lib/_FullInternals.d.ts +23 -11
  37. package/lib/filters/Blur.js +16 -12
  38. package/lib/filters/Brighten.d.ts +1 -0
  39. package/lib/filters/Brighten.js +1 -0
  40. package/lib/filters/Brightness.d.ts +2 -1
  41. package/lib/filters/Brightness.js +4 -4
  42. package/lib/filters/Emboss.js +16 -58
  43. package/lib/filters/Kaleidoscope.js +8 -15
  44. package/lib/filters/Mask.js +8 -8
  45. package/lib/filters/Pixelate.js +16 -29
  46. package/lib/filters/Threshold.d.ts +1 -1
  47. package/lib/filters/Threshold.js +1 -1
  48. package/lib/shapes/Arc.js +8 -6
  49. package/lib/shapes/Arrow.d.ts +3 -6
  50. package/lib/shapes/Arrow.js +75 -47
  51. package/lib/shapes/Circle.d.ts +1 -0
  52. package/lib/shapes/Circle.js +4 -1
  53. package/lib/shapes/Ellipse.d.ts +1 -0
  54. package/lib/shapes/Ellipse.js +4 -1
  55. package/lib/shapes/Image.d.ts +2 -1
  56. package/lib/shapes/Image.js +22 -22
  57. package/lib/shapes/Label.d.ts +2 -3
  58. package/lib/shapes/Label.js +25 -41
  59. package/lib/shapes/Line.d.ts +2 -1
  60. package/lib/shapes/Line.js +5 -2
  61. package/lib/shapes/Path.d.ts +11 -2
  62. package/lib/shapes/Path.js +133 -143
  63. package/lib/shapes/Rect.d.ts +1 -0
  64. package/lib/shapes/Rect.js +4 -1
  65. package/lib/shapes/RegularPolygon.js +2 -2
  66. package/lib/shapes/Ring.d.ts +7 -0
  67. package/lib/shapes/Ring.js +8 -1
  68. package/lib/shapes/Sprite.d.ts +2 -1
  69. package/lib/shapes/Sprite.js +8 -9
  70. package/lib/shapes/Star.d.ts +6 -0
  71. package/lib/shapes/Star.js +5 -1
  72. package/lib/shapes/Text.d.ts +16 -5
  73. package/lib/shapes/Text.js +134 -65
  74. package/lib/shapes/TextPath.d.ts +11 -3
  75. package/lib/shapes/TextPath.js +56 -27
  76. package/lib/shapes/Transformer.js +95 -96
  77. package/lib/shapes/Wedge.js +1 -1
  78. package/lib/types.d.ts +2 -2
  79. package/package.json +5 -20
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 = [
@@ -104,20 +97,6 @@ const ABSOLUTE_OPACITY = 'absoluteOpacity', ABSOLUTE_TRANSFORM = 'absoluteTransf
104
97
  'transformsEnabledChange.konva',
105
98
  ].join(SPACE);
106
99
  let idCounter = 1;
107
- // "perfect drawing" buffer for cache() and toCanvas(): it mirrors the target
108
- // canvas and is drawn back at (x, y) in the target's coordinate space.
109
- // It starts empty and Shape.drawScene sizes it on first use, so nodes
110
- // without buffered shapes never allocate it.
111
- function createBufferCanvas(target, x, y) {
112
- const bufferCanvas = new SceneCanvas({
113
- width: 0,
114
- height: 0,
115
- pixelRatio: target.pixelRatio,
116
- });
117
- bufferCanvas.x = x;
118
- bufferCanvas.y = y;
119
- return bufferCanvas;
120
- }
121
100
  /**
122
101
  * Node constructor. Nodes are entities that can be transformed, layered,
123
102
  * and have bound events. The stage, layers, groups, and shapes all extend Node.
@@ -203,7 +182,7 @@ export class Node {
203
182
  _clearSelfAndDescendantCache(attr) {
204
183
  this._clearCache(attr);
205
184
  // trigger clear cache, so transformer can use it
206
- if (attr === ABSOLUTE_TRANSFORM) {
185
+ if (attr === undefined || attr === ABSOLUTE_TRANSFORM) {
207
186
  this.fire('absoluteTransformChange');
208
187
  }
209
188
  }
@@ -282,23 +261,23 @@ export class Node {
282
261
  conf.y === undefined ||
283
262
  conf.width === undefined ||
284
263
  conf.height === undefined) {
264
+ const wasUnderCache = this._isUnderCache;
265
+ this._isUnderCache = true;
285
266
  rect = this.getClientRect({
286
267
  skipTransform: true,
287
268
  relativeTo: this.getParent() || undefined,
288
269
  });
270
+ this._isUnderCache = wasUnderCache;
289
271
  }
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)) {
272
+ let x = conf.x === undefined ? Math.floor(rect.x) : conf.x, y = conf.y === undefined ? Math.floor(rect.y) : conf.y,
273
+ // round the far edge, not the size, so the last row and column fit in
274
+ 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;
275
+ if (width <= 0 || height <= 0 || !isFinite(x + y + width + height)) {
292
276
  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
277
  return this;
294
278
  }
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;
279
+ width += offset * 2;
280
+ height += offset * 2;
302
281
  x -= offset;
303
282
  y -= offset;
304
283
  const cachedSceneCanvas = new SceneCanvas({
@@ -311,7 +290,6 @@ export class Node {
311
290
  height: 0,
312
291
  willReadFrequently: true,
313
292
  }), sceneContext = cachedSceneCanvas.getContext();
314
- const bufferCanvas = createBufferCanvas(cachedSceneCanvas, x, y);
315
293
  cachedSceneCanvas.isCache = true;
316
294
  this._releaseCanvasCache();
317
295
  this._filterUpToDate = false;
@@ -325,7 +303,7 @@ export class Node {
325
303
  this._isUnderCache = true;
326
304
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
327
305
  try {
328
- this.drawScene(cachedSceneCanvas, this, bufferCanvas);
306
+ this.drawScene(cachedSceneCanvas, this);
329
307
  }
330
308
  catch (e) {
331
309
  Util.releaseCanvas(cachedSceneCanvas._canvas);
@@ -336,8 +314,7 @@ export class Node {
336
314
  // descendants cached their opacity relative to this node while drawing
337
315
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
338
316
  sceneContext.restore();
339
- // the buffer is only needed while drawing
340
- Util.releaseCanvas(bufferCanvas._canvas);
317
+ cachedSceneCanvas._releaseIsolationCanvas();
341
318
  }
342
319
  // this will draw a red border around the cached box for
343
320
  // debugging purposes
@@ -364,6 +341,8 @@ export class Node {
364
341
  x: x,
365
342
  y: y,
366
343
  };
344
+ // Entering cache space changes non-scaling stroke bounds for descendants.
345
+ this._clearSelfAndDescendantCache();
367
346
  this._requestDraw();
368
347
  return this;
369
348
  }
@@ -406,6 +385,8 @@ export class Node {
406
385
  /**
407
386
  * Return client rectangle {x, y, width, height} of node. This rectangle also include all styling (strokes, shadows, etc).
408
387
  * The purpose of the method is similar to getBoundingClientRect API of the DOM.
388
+ * Non-scaling stroke padding is converted from its drawing canvas to the requested coordinates.
389
+ * Cached strokes use the cache's coordinates; their pixels scale with the cached bitmap.
409
390
  * @method
410
391
  * @name Konva.Node#getClientRect
411
392
  * @param {Object} config
@@ -444,28 +425,22 @@ export class Node {
444
425
  // redefine in Container and Shape
445
426
  throw new Error('abstract "getClientRect" method call');
446
427
  }
447
- _transformedRect(rect, top) {
448
- const points = [
449
- { x: rect.x, y: rect.y },
450
- { x: rect.x + rect.width, y: rect.y },
451
- { x: rect.x + rect.width, y: rect.y + rect.height },
452
- { x: rect.x, y: rect.y + rect.height },
453
- ];
454
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
455
- const trans = this.getAbsoluteTransform(top);
456
- points.forEach(function (point) {
457
- const transformed = trans.point(point);
458
- minX = Math.min(minX, transformed.x);
459
- minY = Math.min(minY, transformed.y);
460
- maxX = Math.max(maxX, transformed.x);
461
- maxY = Math.max(maxY, transformed.y);
462
- });
463
- return {
464
- x: minX,
465
- y: minY,
466
- width: maxX - minX,
467
- height: maxY - minY,
428
+ _getCachedSceneRect(config) {
429
+ const cache = config._forDrawing && !this._isUnderCache && this._getCanvasCache();
430
+ if (!cache)
431
+ return;
432
+ const rect = {
433
+ x: cache.x,
434
+ y: cache.y,
435
+ width: cache.scene.width / cache.scene.pixelRatio,
436
+ height: cache.scene.height / cache.scene.pixelRatio,
468
437
  };
438
+ return config.skipTransform
439
+ ? rect
440
+ : this._transformedRect(rect, config.relativeTo);
441
+ }
442
+ _transformedRect(rect, top) {
443
+ return this.getAbsoluteTransform(top)._getTransformedRect(rect);
469
444
  }
470
445
  _drawCachedSceneCanvas(context) {
471
446
  context.save();
@@ -503,7 +478,11 @@ export class Node {
503
478
  const ratio = sceneCanvas.pixelRatio;
504
479
  filterCanvas.setSizeIfChanged(sceneCanvas._logicalWidth, sceneCanvas._logicalHeight);
505
480
  if (useNativeOnly) {
506
- const finalFilter = filters.join(' ');
481
+ // Canvas filters use backing-pixel coordinates, independent of the CTM.
482
+ // Scale length tokens, leaving colors, percentages and URL references alone.
483
+ const finalFilter = filters
484
+ .join(' ')
485
+ .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
486
  filterContext.clear();
508
487
  filterContext.save();
509
488
  filterContext.setAttr('filter', finalFilter);
@@ -524,7 +503,7 @@ export class Node {
524
503
  if (typeof filter === 'string') {
525
504
  filter = parseCSSFilters(filter);
526
505
  }
527
- filter.call(this, imageData);
506
+ filter.call(this, imageData, ratio);
528
507
  }
529
508
  filterContext.putImageData(imageData, 0, 0);
530
509
  }
@@ -749,15 +728,15 @@ export class Node {
749
728
  this._clearSelfAndDescendantCache(LISTENING);
750
729
  }
751
730
  _remove() {
752
- // every cached attr that is calculated via node tree
753
- // traversal must be cleared when removing a node
754
- this._clearCaches();
755
731
  const parent = this.getParent();
756
732
  if (parent && parent.children) {
757
733
  parent.children.splice(this.index, 1);
758
734
  parent._setChildrenIndices();
759
735
  this.parent = null;
760
736
  }
737
+ // every cached attr that is calculated via node tree
738
+ // traversal must be cleared when removing a node
739
+ this._clearCaches();
761
740
  }
762
741
  /**
763
742
  * remove and destroy a node. Kill it and delete forever! You should not reuse node after destroy().
@@ -1001,6 +980,10 @@ export class Node {
1001
980
  // for performance reasons, lets batch transform reset
1002
981
  // so it work faster
1003
982
  _batchTransformChanges(func) {
983
+ if (this._batchingTransformChange) {
984
+ func();
985
+ return;
986
+ }
1004
987
  this._batchingTransformChange = true;
1005
988
  try {
1006
989
  func();
@@ -1308,7 +1291,8 @@ export class Node {
1308
1291
  */
1309
1292
  toObject() {
1310
1293
  var _a;
1311
- let attrs = this.getAttrs(), key, val, getter, defaultValue, nonPlainObject;
1294
+ const attrs = this.getAttrs();
1295
+ let key, val, nonPlainObject;
1312
1296
  const obj = {
1313
1297
  attrs: {},
1314
1298
  className: this.getClassName(),
@@ -1322,18 +1306,18 @@ export class Node {
1322
1306
  if (nonPlainObject) {
1323
1307
  continue;
1324
1308
  }
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;
1309
+ // only the getters generated by Factory carry a default, so an explicit
1310
+ // value equal to a computed one (Text width, dragDistance) is kept
1311
+ // Shared filter parameters can distinguish an explicit value from unset.
1312
+ if (((_a = this['get' + Util._capitalize(key)]) === null || _a === void 0 ? void 0 : _a._def) !== val ||
1313
+ key === 'brightness' ||
1314
+ key === 'threshold') {
1315
+ obj.attrs[key] =
1316
+ key === 'filters' && Util._isArray(val)
1317
+ ? val.filter((filter) => typeof filter === 'string')
1318
+ : Util.isObject(val)
1319
+ ? Util._prepareToStringify(val)
1320
+ : val;
1337
1321
  }
1338
1322
  }
1339
1323
  return obj;
@@ -1707,13 +1691,14 @@ export class Node {
1707
1691
  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
1692
  }
1709
1693
  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),
1694
+ width: config.width ||
1695
+ Math.max(0, Math.ceil(box.x + box.width - x)) ||
1696
+ (stage ? stage.width() : 0),
1711
1697
  height: config.height ||
1712
- Math.ceil(box.height) ||
1698
+ Math.max(0, Math.ceil(box.y + box.height - y)) ||
1713
1699
  (stage ? stage.height() : 0),
1714
1700
  pixelRatio: pixelRatio,
1715
1701
  }), context = canvas.getContext();
1716
- const bufferCanvas = createBufferCanvas(canvas, x, y);
1717
1702
  if (config.imageSmoothingEnabled === false) {
1718
1703
  context._context.imageSmoothingEnabled = false;
1719
1704
  }
@@ -1721,10 +1706,9 @@ export class Node {
1721
1706
  if (x || y) {
1722
1707
  context.translate(-1 * x, -1 * y);
1723
1708
  }
1724
- this.drawScene(canvas, undefined, bufferCanvas);
1709
+ this.drawScene(canvas);
1725
1710
  context.restore();
1726
- // the buffer is only needed while drawing
1727
- Util.releaseCanvas(bufferCanvas._canvas);
1711
+ canvas._releaseIsolationCanvas();
1728
1712
  return canvas;
1729
1713
  }
1730
1714
  /**
@@ -1738,8 +1722,9 @@ export class Node {
1738
1722
  * @param {Number} [config.width] width of canvas section
1739
1723
  * @param {Number} [config.height] height of canvas section
1740
1724
  * @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.
1725
+ * Higher pixel ratios increase export resolution. Cached nodes keep their cache resolution.
1726
+ * Rebuild caches at the export pixel ratio to preserve detail.
1727
+ * The pixel ratio multiplies the dimensions of the exported image.
1743
1728
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1744
1729
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1745
1730
  * @example
@@ -1765,15 +1750,17 @@ export class Node {
1765
1750
  * you can specify the quality from 0 to 1, where 0 is very poor quality and 1
1766
1751
  * is very high quality
1767
1752
  * @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.
1753
+ * Higher pixel ratios increase export resolution. Cached nodes keep their cache resolution.
1754
+ * Rebuild caches at the export pixel ratio to preserve detail.
1755
+ * The pixel ratio multiplies the dimensions of the exported image.
1770
1756
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1771
1757
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1772
1758
  * @returns {String}
1773
1759
  */
1774
1760
  toDataURL(config) {
1761
+ var _a;
1775
1762
  config = config || {};
1776
- const mimeType = config.mimeType || null, quality = config.quality || null;
1763
+ const mimeType = config.mimeType || null, quality = (_a = config.quality) !== null && _a !== void 0 ? _a : null;
1777
1764
  const url = this._toKonvaCanvas(config).toDataURL(mimeType, quality);
1778
1765
  if (config.callback) {
1779
1766
  config.callback(url);
@@ -1799,8 +1786,9 @@ export class Node {
1799
1786
  * you can specify the quality from 0 to 1, where 0 is very poor quality and 1
1800
1787
  * is very high quality
1801
1788
  * @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.
1789
+ * Higher pixel ratios increase export resolution. Cached nodes keep their cache resolution.
1790
+ * Rebuild caches at the export pixel ratio to preserve detail.
1791
+ * The pixel ratio multiplies the dimensions of the exported image.
1804
1792
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1805
1793
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1806
1794
  * @return {Promise<Image>}
@@ -1814,13 +1802,11 @@ export class Node {
1814
1802
  toImage(config) {
1815
1803
  return new Promise((resolve, reject) => {
1816
1804
  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) {
1805
+ const { callback, ...rest } = config || {};
1806
+ Util._urlToImage(this.toDataURL(rest), function (img) {
1821
1807
  resolve(img);
1822
1808
  callback === null || callback === void 0 ? void 0 : callback(img);
1823
- });
1809
+ }, reject);
1824
1810
  }
1825
1811
  catch (err) {
1826
1812
  reject(err);
@@ -1840,8 +1826,9 @@ export class Node {
1840
1826
  * @param {Number} [config.width] width of canvas section
1841
1827
  * @param {Number} [config.height] height of canvas section
1842
1828
  * @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.
1829
+ * Higher pixel ratios increase export resolution. Cached nodes keep their cache resolution.
1830
+ * Rebuild caches at the export pixel ratio to preserve detail.
1831
+ * The pixel ratio multiplies the dimensions of the exported image.
1845
1832
  * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000.
1846
1833
  * @param {Boolean} [config.imageSmoothingEnabled] set this to false if you want to disable imageSmoothing
1847
1834
  * @example
@@ -1851,17 +1838,15 @@ export class Node {
1851
1838
  toBlob(config) {
1852
1839
  return new Promise((resolve, reject) => {
1853
1840
  try {
1854
- const callback = config === null || config === void 0 ? void 0 : config.callback;
1855
- if (callback)
1856
- delete config.callback;
1857
1841
  this.toCanvas(config).toBlob((blob) => {
1842
+ var _a;
1858
1843
  // the canvas reports a failed encode by passing null
1859
1844
  if (!blob) {
1860
1845
  reject(new Error('Konva: toBlob() failed, the canvas was not encoded'));
1861
1846
  return;
1862
1847
  }
1863
1848
  resolve(blob);
1864
- callback === null || callback === void 0 ? void 0 : callback(blob);
1849
+ (_a = config === null || config === void 0 ? void 0 : config.callback) === null || _a === void 0 ? void 0 : _a.call(config, blob);
1865
1850
  }, config === null || config === void 0 ? void 0 : config.mimeType, config === null || config === void 0 ? void 0 : config.quality);
1866
1851
  }
1867
1852
  catch (err) {
@@ -2154,6 +2139,7 @@ export class Node {
2154
2139
  }
2155
2140
  // drag & drop
2156
2141
  _createDragElement(evt) {
2142
+ var _a;
2157
2143
  const pointerId = evt ? evt.pointerId : undefined;
2158
2144
  const stage = this.getStage();
2159
2145
  const ap = this.getAbsolutePosition();
@@ -2163,6 +2149,12 @@ export class Node {
2163
2149
  const pos = stage._getPointerById(pointerId) ||
2164
2150
  stage._changedPointerPositions[0] ||
2165
2151
  ap;
2152
+ const type = ((_a = evt === null || evt === void 0 ? void 0 : evt.evt) === null || _a === void 0 ? void 0 : _a.type)
2153
+ ? Util._getEventType(evt.evt.type)
2154
+ : stage._pointerEventType;
2155
+ // drags follow mouse and touch window events only, so a drag started from
2156
+ // a pointer event stays unbound until such an event attaches its pointer
2157
+ const bound = type !== 'pointer';
2166
2158
  DD._dragElements.set(this._id, {
2167
2159
  node: this,
2168
2160
  startPointerPos: pos,
@@ -2171,7 +2163,10 @@ export class Node {
2171
2163
  y: pos.y - ap.y,
2172
2164
  },
2173
2165
  dragStatus: 'ready',
2174
- pointerId,
2166
+ pointerId: bound
2167
+ ? (pointerId !== null && pointerId !== void 0 ? pointerId : ('id' in pos ? pos.id : undefined))
2168
+ : undefined,
2169
+ pointerEventType: bound ? type : undefined,
2175
2170
  startEvent: evt,
2176
2171
  });
2177
2172
  }
@@ -2181,6 +2176,7 @@ export class Node {
2181
2176
  * @name Konva.Node#startDrag
2182
2177
  */
2183
2178
  startDrag(evt, bubbleEvent = true) {
2179
+ var _a;
2184
2180
  if (!DD._dragElements.has(this._id)) {
2185
2181
  this._createDragElement(evt);
2186
2182
  }
@@ -2190,6 +2186,7 @@ export class Node {
2190
2186
  return;
2191
2187
  }
2192
2188
  elem.dragStatus = 'dragging';
2189
+ (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._cancelClick(elem.pointerId, elem.pointerEventType);
2193
2190
  this.fire('dragstart', {
2194
2191
  type: 'dragstart',
2195
2192
  target: this,
@@ -2235,11 +2232,12 @@ export class Node {
2235
2232
  */
2236
2233
  stopDrag(evt) {
2237
2234
  const elem = DD._dragElements.get(this._id);
2238
- if (elem) {
2239
- elem.dragStatus = 'stopped';
2235
+ if (!elem) {
2236
+ return;
2240
2237
  }
2241
- DD._endDragBefore(evt);
2242
- DD._endDragAfter(evt);
2238
+ elem.dragStatus = 'stopped';
2239
+ DD._endDragBefore(evt, undefined, elem);
2240
+ DD._endDragAfter(evt, elem);
2243
2241
  }
2244
2242
  setDraggable(draggable) {
2245
2243
  this._setAttr('draggable', draggable);
@@ -2262,7 +2260,7 @@ export class Node {
2262
2260
  if (!canDrag) {
2263
2261
  return;
2264
2262
  }
2265
- if (this.isDragging()) {
2263
+ if (DD._dragElements.has(this._id)) {
2266
2264
  return;
2267
2265
  }
2268
2266
  let hasDraggingChild = false;
@@ -2364,10 +2362,11 @@ export class Node {
2364
2362
  obj.attrs.container = container;
2365
2363
  }
2366
2364
  if (!Konva[className]) {
2365
+ const fallback = children ? 'Group' : 'Shape';
2367
2366
  Util.warn('Can not find a node with class name "' +
2368
2367
  className +
2369
- '". Fallback to "Shape".');
2370
- className = 'Shape';
2368
+ `". Fallback to "${fallback}".`);
2369
+ className = fallback;
2371
2370
  }
2372
2371
  const Class = Konva[className];
2373
2372
  no = new Class(obj.attrs);
@@ -2406,6 +2405,13 @@ Node.prototype.on('visibleChange.konva', function () {
2406
2405
  });
2407
2406
  Node.prototype.on('listeningChange.konva', function () {
2408
2407
  this._clearSelfAndDescendantCache(LISTENING);
2408
+ for (let parent = this.getParent(); parent; parent = parent.getParent()) {
2409
+ const cache = parent._getCanvasCache();
2410
+ if (cache === null || cache === void 0 ? void 0 : cache.hit) {
2411
+ Util.releaseCanvas(cache.hit._canvas);
2412
+ cache.hit = null;
2413
+ }
2414
+ }
2409
2415
  });
2410
2416
  Node.prototype.on('opacityChange.konva', function () {
2411
2417
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
@@ -2802,6 +2808,8 @@ addGetterSetter(Node, 'filters', undefined, function (val) {
2802
2808
  * get/set filters. Supports function filters, CSS filter strings, or mixed arrays.
2803
2809
  * CSS filters are applied using native browser performance when possible, function filters use ImageData manipulation.
2804
2810
  * CSS filters automatically fall back to function filters in unsupported browsers.
2811
+ * Blur radii, pixelation sizes and CSS lengths use node coordinates, independent of cache pixelRatio.
2812
+ * Custom filters receive (imageData, pixelRatio). ImageData contains full-resolution backing pixels.
2805
2813
  * @name Konva.Node#filters
2806
2814
  * @method
2807
2815
  * @param {Array} filters array of filter functions and/or CSS filter strings
@@ -2810,7 +2818,8 @@ addGetterSetter(Node, 'filters', undefined, function (val) {
2810
2818
  * // get filters
2811
2819
  * var filters = node.filters();
2812
2820
  *
2813
- * // set CSS filters only (no caching required, uses native performance)
2821
+ * // set CSS filters only (caching required, uses native performance)
2822
+ * node.cache();
2814
2823
  * node.filters(['blur(5px)', 'brightness(1.2)', 'contrast(1.5)']);
2815
2824
  *
2816
2825
  * // 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;