konva 10.3.0 → 10.3.2

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.
package/konva.js CHANGED
@@ -5,10 +5,10 @@
5
5
  })(this, (function () { 'use strict';
6
6
 
7
7
  /*
8
- * Konva JavaScript Framework v10.3.0
8
+ * Konva JavaScript Framework v10.3.2
9
9
  * http://konvajs.org/
10
10
  * Licensed under the MIT
11
- * Date: Thu Apr 30 2026
11
+ * Date: Wed Aug 26 2026
12
12
  *
13
13
  * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS)
14
14
  * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva)
@@ -35,7 +35,7 @@
35
35
  : {};
36
36
  const Konva$2 = {
37
37
  _global: glob,
38
- version: '10.3.0',
38
+ version: '10.3.2',
39
39
  isBrowser: detectBrowser(),
40
40
  isUnminified: /param/.test(function (param) { }.toString()),
41
41
  dblClickWindow: 400,
@@ -465,7 +465,7 @@ js: import "konva/skia-backend";
465
465
  }
466
466
  }
467
467
  // CONSTANTS
468
- const OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', OBJECT_BOOLEAN = '[object Boolean]', PI_OVER_DEG180 = Math.PI / 180, DEG180_OVER_PI = 180 / Math.PI, HASH = '#', EMPTY_STRING$1 = '', ZERO = '0', KONVA_WARNING = 'Konva warning: ', KONVA_ERROR = 'Konva error: ', RGB_PAREN = 'rgb(', COLORS = {
468
+ const OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', OBJECT_BOOLEAN = '[object Boolean]', PI_OVER_DEG180 = Math.PI / 180, DEG180_OVER_PI = 180 / Math.PI, HASH = '#', EMPTY_STRING$1 = '', ZERO = '0', KONVA_WARNING = 'Konva warning: ', KONVA_ERROR = 'Konva error: ', COLORS = {
469
469
  aliceblue: [240, 248, 255],
470
470
  antiquewhite: [250, 235, 215],
471
471
  aqua: [0, 255, 255],
@@ -489,7 +489,7 @@ js: import "konva/skia-backend";
489
489
  cyan: [0, 255, 255],
490
490
  darkblue: [0, 0, 139],
491
491
  darkcyan: [0, 139, 139],
492
- darkgoldenrod: [184, 132, 11],
492
+ darkgoldenrod: [184, 134, 11],
493
493
  darkgray: [169, 169, 169],
494
494
  darkgreen: [0, 100, 0],
495
495
  darkgrey: [169, 169, 169],
@@ -512,7 +512,7 @@ js: import "konva/skia-backend";
512
512
  dimgrey: [105, 105, 105],
513
513
  dodgerblue: [30, 144, 255],
514
514
  firebrick: [178, 34, 34],
515
- floralwhite: [255, 255, 240],
515
+ floralwhite: [255, 250, 240],
516
516
  forestgreen: [34, 139, 34],
517
517
  fuchsia: [255, 0, 255],
518
518
  gainsboro: [220, 220, 220],
@@ -582,7 +582,7 @@ js: import "konva/skia-backend";
582
582
  peachpuff: [255, 218, 185],
583
583
  peru: [205, 133, 63],
584
584
  pink: [255, 192, 203],
585
- plum: [221, 160, 203],
585
+ plum: [221, 160, 221],
586
586
  powderblue: [176, 224, 230],
587
587
  purple: [128, 0, 128],
588
588
  rebeccapurple: [102, 51, 153],
@@ -598,9 +598,9 @@ js: import "konva/skia-backend";
598
598
  silver: [192, 192, 192],
599
599
  skyblue: [135, 206, 235],
600
600
  slateblue: [106, 90, 205],
601
- slategray: [119, 128, 144],
602
- slategrey: [119, 128, 144],
603
- snow: [255, 255, 250],
601
+ slategray: [112, 128, 144],
602
+ slategrey: [112, 128, 144],
603
+ snow: [255, 250, 250],
604
604
  springgreen: [0, 255, 127],
605
605
  steelblue: [70, 130, 180],
606
606
  tan: [210, 180, 140],
@@ -614,15 +614,66 @@ js: import "konva/skia-backend";
614
614
  white: [255, 255, 255],
615
615
  whitesmoke: [245, 245, 245],
616
616
  yellow: [255, 255, 0],
617
- yellowgreen: [154, 205, 5],
618
- }, RGB_REGEX = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;
619
- let animQueue = [];
617
+ yellowgreen: [154, 205, 50],
618
+ };
620
619
  // Cache for canvas farbling detection
621
620
  let _isCanvasFarblingActive = null;
622
- const req = (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame) ||
623
- function (f) {
621
+ // A stage may be rendered in another window than the one Konva was imported
622
+ // into, and a window that is not visible gives almost no frames. So frames are
623
+ // asked from the window of the stage, and the callbacks are kept per window
624
+ const defaultWindow = typeof window !== 'undefined' ? window : {};
625
+ const animQueues = new WeakMap();
626
+ const requestFrame = (win, f) => {
627
+ if (typeof win.requestAnimationFrame === 'function') {
628
+ win.requestAnimationFrame(f);
629
+ }
630
+ else if (typeof requestAnimationFrame !== 'undefined') {
631
+ requestAnimationFrame(f);
632
+ }
633
+ else {
624
634
  setTimeout(f, 16); // 60fps ≈ 16.67ms per frame
625
- };
635
+ }
636
+ };
637
+ const capitalizeCache = new Map();
638
+ // Split the components of rgb()/hsl(). CSS separates them with commas (legacy
639
+ // syntax), or with spaces and a slash before the alpha (CSS Color 4 syntax),
640
+ // but never with both. Keep the two apart, so that a space inside a
641
+ // comma-separated color adds no component. A component the user left empty
642
+ // stays as "", which then fails the color.
643
+ const splitColorComponents = (str) => {
644
+ const components = str.trim();
645
+ return components.indexOf(',') === -1
646
+ ? components.split(/\s*\/\s*|\s+/)
647
+ : components.split(/\s*,\s*/);
648
+ };
649
+ // A CSS number: "50", "-0.5", ".5", "1e2". Everything else, from "50abc" to
650
+ // "0x10" and "1.2.3", is not a number and makes the color fail.
651
+ const NUMBER_SOURCE = '[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?';
652
+ // A component is a number with an optional "%" sign.
653
+ const COLOR_COMPONENT_REGEX = new RegExp(`^(${NUMBER_SOURCE})(%?)$`, 'i');
654
+ // Parse one color component. 100% is `max`: 255 for the color channels of
655
+ // rgb(), 1 for the alpha, 100 for the saturation and the lightness of hsl().
656
+ const parseColorComponent = (value, max) => {
657
+ const match = COLOR_COMPONENT_REGEX.exec(value);
658
+ if (!match) {
659
+ return NaN;
660
+ }
661
+ return match[2] ? (Number(match[1]) / 100) * max : Number(match[1]);
662
+ };
663
+ // parseInt() stops at the first character it can not read, so "#0g0000" would
664
+ // give a valid black instead of failing. The hex parsers test the shape first.
665
+ const HEX_COLOR_REGEX = /^#[0-9a-f]+$/i;
666
+ // Keep a fraction in [0, 1]. NaN stays NaN, so a bad value still fails.
667
+ const clamp01 = (value) => Math.min(Math.max(value, 0), 1);
668
+ // The hue of hsl() is the same number, with a CSS Color 4 angle unit
669
+ // instead of the "%" sign. No unit means degrees.
670
+ const HUE_REGEX = new RegExp(`^(${NUMBER_SOURCE})(deg|grad|rad|turn)?$`, 'i');
671
+ const HUE_UNITS = {
672
+ deg: 1,
673
+ grad: 0.9,
674
+ rad: DEG180_OVER_PI,
675
+ turn: 360,
676
+ };
626
677
  /**
627
678
  * @namespace Util
628
679
  * @memberof Konva
@@ -680,17 +731,20 @@ js: import "konva/skia-backend";
680
731
  return -1;
681
732
  }
682
733
  },
683
- requestAnimFrame(callback) {
684
- animQueue.push(callback);
685
- if (animQueue.length === 1) {
686
- req(function () {
687
- const queue = animQueue;
688
- animQueue = [];
734
+ requestAnimFrame(callback, win) {
735
+ const target = (win && !win.closed && win) || defaultWindow;
736
+ let queue = animQueues.get(target);
737
+ if (!queue) {
738
+ queue = [];
739
+ animQueues.set(target, queue);
740
+ requestFrame(target, function () {
741
+ animQueues.delete(target);
689
742
  queue.forEach(function (cb) {
690
743
  cb();
691
744
  });
692
745
  });
693
746
  }
747
+ queue.push(callback);
694
748
  },
695
749
  createCanvasElement() {
696
750
  ensureBrowser();
@@ -707,12 +761,9 @@ js: import "konva/skia-backend";
707
761
  return document.createElement('img');
708
762
  },
709
763
  _isInDocument(el) {
710
- while ((el = el.parentNode)) {
711
- if (el == document) {
712
- return true;
713
- }
714
- }
715
- return false;
764
+ // not `el.parentNode == document`, because the element may belong to
765
+ // another document: an iframe, or a popout window
766
+ return !!el.isConnected;
716
767
  },
717
768
  /*
718
769
  * arg can be an image object or image data
@@ -842,50 +893,29 @@ js: import "konva/skia-backend";
842
893
  * var rgb = Konva.Util.getRGB('rgb(0,0,255)');
843
894
  */
844
895
  getRGB(color) {
845
- let rgb;
846
- // color string
847
- if (color in COLORS) {
848
- rgb = COLORS[color];
849
- return {
850
- r: rgb[0],
851
- g: rgb[1],
852
- b: rgb[2],
853
- };
854
- }
855
- else if (color[0] === HASH) {
856
- // hex
857
- return this._hexToRgb(color.substring(1));
858
- }
859
- else if (color.substr(0, 4) === RGB_PAREN) {
860
- // rgb string
861
- rgb = RGB_REGEX.exec(color.replace(/ /g, ''));
862
- return {
863
- r: parseInt(rgb[1], 10),
864
- g: parseInt(rgb[2], 10),
865
- b: parseInt(rgb[3], 10),
866
- };
867
- }
868
- else {
869
- // default
870
- return {
871
- r: 0,
872
- g: 0,
873
- b: 0,
874
- };
875
- }
896
+ var _a;
897
+ // black for a color we can not parse
898
+ const { r = 0, g = 0, b = 0 } = (_a = Util.colorToRGBA(color)) !== null && _a !== void 0 ? _a : {};
899
+ return { r, g, b };
876
900
  },
877
901
  // convert any color string to RGBA object
878
902
  // from https://github.com/component/color-parser
879
903
  colorToRGBA(str) {
880
- str = str || 'black';
881
- return (Util._namedColorToRBA(str) ||
904
+ // a CSS custom property keeps the space after the colon,
905
+ // so "--brand: #ff0000" gives us " #ff0000"
906
+ str = (str || '').trim() || 'black';
907
+ const color = Util._namedColorToRBA(str) ||
882
908
  Util._hex3ColorToRGBA(str) ||
883
909
  Util._hex4ColorToRGBA(str) ||
884
910
  Util._hex6ColorToRGBA(str) ||
885
911
  Util._hex8ColorToRGBA(str) ||
886
912
  Util._rgbColorToRGBA(str) ||
887
- Util._rgbaColorToRGBA(str) ||
888
- Util._hslColorToRGBA(str));
913
+ Util._hslColorToRGBA(str);
914
+ // a NaN component stays invisible until it reaches the canvas and drops the
915
+ // shape, so a color we can not fully parse must fail as a whole
916
+ if (color && [color.r, color.g, color.b, color.a].every(Util._isNumber)) {
917
+ return color;
918
+ }
889
919
  },
890
920
  // Parse named css color. Like "green"
891
921
  _namedColorToRBA(str) {
@@ -897,43 +927,29 @@ js: import "konva/skia-backend";
897
927
  r: c[0],
898
928
  g: c[1],
899
929
  b: c[2],
900
- a: 1,
930
+ a: c.length > 3 ? c[3] : 1,
901
931
  };
902
932
  },
903
- // Parse rgb(n, n, n)
933
+ // Parse rgb(n, n, n), rgba(n, n, n, n) and rgb(n n n / n)
904
934
  _rgbColorToRGBA(str) {
905
- if (str.indexOf('rgb(') === 0) {
906
- str = str.match(/rgb\(([^)]+)\)/)[1];
907
- const parts = str.split(/ *, */).map(Number);
908
- return {
909
- r: parts[0],
910
- g: parts[1],
911
- b: parts[2],
912
- a: 1,
913
- };
935
+ const match = /^rgba?\(([^)]*)\)$/i.exec(str);
936
+ if (!match) {
937
+ return;
914
938
  }
915
- },
916
- // Parse rgba(n, n, n, n)
917
- _rgbaColorToRGBA(str) {
918
- if (str.indexOf('rgba(') === 0) {
919
- str = str.match(/rgba\(([^)]+)\)/)[1];
920
- const parts = str.split(/ *, */).map((n, index) => {
921
- if (n.slice(-1) === '%') {
922
- return index === 3 ? parseInt(n) / 100 : (parseInt(n) / 100) * 255;
923
- }
924
- return Number(n);
925
- });
926
- return {
927
- r: parts[0],
928
- g: parts[1],
929
- b: parts[2],
930
- a: parts[3],
931
- };
939
+ const parts = splitColorComponents(match[1]);
940
+ if (parts.length < 3 || parts.length > 4) {
941
+ return;
932
942
  }
943
+ return {
944
+ r: parseColorComponent(parts[0], 255),
945
+ g: parseColorComponent(parts[1], 255),
946
+ b: parseColorComponent(parts[2], 255),
947
+ a: parts.length > 3 ? parseColorComponent(parts[3], 1) : 1,
948
+ };
933
949
  },
934
950
  // Parse #nnnnnnnn
935
951
  _hex8ColorToRGBA(str) {
936
- if (str[0] === '#' && str.length === 9) {
952
+ if (str.length === 9 && HEX_COLOR_REGEX.test(str)) {
937
953
  return {
938
954
  r: parseInt(str.slice(1, 3), 16),
939
955
  g: parseInt(str.slice(3, 5), 16),
@@ -944,7 +960,7 @@ js: import "konva/skia-backend";
944
960
  },
945
961
  // Parse #nnnnnn
946
962
  _hex6ColorToRGBA(str) {
947
- if (str[0] === '#' && str.length === 7) {
963
+ if (str.length === 7 && HEX_COLOR_REGEX.test(str)) {
948
964
  return {
949
965
  r: parseInt(str.slice(1, 3), 16),
950
966
  g: parseInt(str.slice(3, 5), 16),
@@ -955,7 +971,7 @@ js: import "konva/skia-backend";
955
971
  },
956
972
  // Parse #nnnn
957
973
  _hex4ColorToRGBA(str) {
958
- if (str[0] === '#' && str.length === 5) {
974
+ if (str.length === 5 && HEX_COLOR_REGEX.test(str)) {
959
975
  return {
960
976
  r: parseInt(str[1] + str[1], 16),
961
977
  g: parseInt(str[2] + str[2], 16),
@@ -966,7 +982,7 @@ js: import "konva/skia-backend";
966
982
  },
967
983
  // Parse #nnn
968
984
  _hex3ColorToRGBA(str) {
969
- if (str[0] === '#' && str.length === 4) {
985
+ if (str.length === 4 && HEX_COLOR_REGEX.test(str)) {
970
986
  return {
971
987
  r: parseInt(str[1] + str[1], 16),
972
988
  g: parseInt(str[2] + str[2], 16),
@@ -976,63 +992,69 @@ js: import "konva/skia-backend";
976
992
  }
977
993
  },
978
994
  // Code adapted from https://github.com/Qix-/color-convert/blob/master/conversions.js#L244
995
+ // Parse hsl(h, s%, l%), hsla(h, s%, l%, n) and hsl(h s% l% / n)
979
996
  _hslColorToRGBA(str) {
980
- // Check hsl() format
981
- if (/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(str)) {
982
- // Extract h, s, l
983
- const [_, ...hsl] = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(str);
984
- const h = Number(hsl[0]) / 360;
985
- const s = Number(hsl[1]) / 100;
986
- const l = Number(hsl[2]) / 100;
987
- let t2;
988
- let t3;
997
+ const match = /^hsla?\(([^)]*)\)$/i.exec(str);
998
+ if (!match) {
999
+ return;
1000
+ }
1001
+ const parts = splitColorComponents(match[1]);
1002
+ if (parts.length < 3 || parts.length > 4) {
1003
+ return;
1004
+ }
1005
+ // a hue we can not parse gives a gray color instead of a NaN one,
1006
+ // so colorToRGBA() can not catch it at the end
1007
+ const hue = HUE_REGEX.exec(parts[0]);
1008
+ if (!hue) {
1009
+ return;
1010
+ }
1011
+ const unit = hue[2];
1012
+ const degrees = Number(hue[1]) * (unit ? HUE_UNITS[unit.toLowerCase()] : 1);
1013
+ if (!isFinite(degrees)) {
1014
+ return;
1015
+ }
1016
+ // the hue is an angle, so keep it in [0, 360) to also accept
1017
+ // negative angles and angles over one full turn
1018
+ const h = (((degrees % 360) + 360) % 360) / 360;
1019
+ // the saturation and the lightness are percentages of 1, written with or
1020
+ // without the "%" sign, so read them out of 100 and then scale them down.
1021
+ // CSS keeps them in [0, 1]; out of that range the math gives a negative
1022
+ // channel, which the canvas can not read at all.
1023
+ const s = clamp01(parseColorComponent(parts[1], 100) / 100);
1024
+ const l = clamp01(parseColorComponent(parts[2], 100) / 100);
1025
+ const a = parts.length > 3 ? parseColorComponent(parts[3], 1) : 1;
1026
+ const t2 = l < 0.5 ? l * (1 + s) : l + s - l * s;
1027
+ const t1 = 2 * l - t2;
1028
+ const rgb = [0, 0, 0];
1029
+ for (let i = 0; i < 3; i++) {
1030
+ let t3 = h + (1 / 3) * -(i - 1);
1031
+ if (t3 < 0) {
1032
+ t3++;
1033
+ }
1034
+ if (t3 > 1) {
1035
+ t3--;
1036
+ }
989
1037
  let val;
990
- if (s === 0) {
991
- val = l * 255;
992
- return {
993
- r: Math.round(val),
994
- g: Math.round(val),
995
- b: Math.round(val),
996
- a: 1,
997
- };
1038
+ if (6 * t3 < 1) {
1039
+ val = t1 + (t2 - t1) * 6 * t3;
1040
+ }
1041
+ else if (2 * t3 < 1) {
1042
+ val = t2;
998
1043
  }
999
- if (l < 0.5) {
1000
- t2 = l * (1 + s);
1044
+ else if (3 * t3 < 2) {
1045
+ val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
1001
1046
  }
1002
1047
  else {
1003
- t2 = l + s - l * s;
1004
- }
1005
- const t1 = 2 * l - t2;
1006
- const rgb = [0, 0, 0];
1007
- for (let i = 0; i < 3; i++) {
1008
- t3 = h + (1 / 3) * -(i - 1);
1009
- if (t3 < 0) {
1010
- t3++;
1011
- }
1012
- if (t3 > 1) {
1013
- t3--;
1014
- }
1015
- if (6 * t3 < 1) {
1016
- val = t1 + (t2 - t1) * 6 * t3;
1017
- }
1018
- else if (2 * t3 < 1) {
1019
- val = t2;
1020
- }
1021
- else if (3 * t3 < 2) {
1022
- val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
1023
- }
1024
- else {
1025
- val = t1;
1026
- }
1027
- rgb[i] = val * 255;
1048
+ val = t1;
1028
1049
  }
1029
- return {
1030
- r: Math.round(rgb[0]),
1031
- g: Math.round(rgb[1]),
1032
- b: Math.round(rgb[2]),
1033
- a: 1,
1034
- };
1050
+ rgb[i] = val * 255;
1035
1051
  }
1052
+ return {
1053
+ r: Math.round(rgb[0]),
1054
+ g: Math.round(rgb[1]),
1055
+ b: Math.round(rgb[2]),
1056
+ a,
1057
+ };
1036
1058
  },
1037
1059
  /**
1038
1060
  * check intersection of two client rectangles
@@ -1084,8 +1106,14 @@ js: import "konva/skia-backend";
1084
1106
  _getRotation(radians) {
1085
1107
  return Konva$2.angleDeg ? Util.radToDeg(radians) : radians;
1086
1108
  },
1109
+ // Memoized — called per-attr per setAttrs; input vocabulary is bounded.
1087
1110
  _capitalize(str) {
1088
- return str.charAt(0).toUpperCase() + str.slice(1);
1111
+ const cached = capitalizeCache.get(str);
1112
+ if (cached !== undefined)
1113
+ return cached;
1114
+ const out = str.charAt(0).toUpperCase() + str.slice(1);
1115
+ capitalizeCache.set(str, out);
1116
+ return out;
1089
1117
  },
1090
1118
  throw(str) {
1091
1119
  throw new Error(KONVA_ERROR + str);
@@ -1984,6 +2012,16 @@ js: import "konva/skia-backend";
1984
2012
  shape._fillFunc(this);
1985
2013
  }
1986
2014
  _fillPattern(shape) {
2015
+ // `imageSmoothingEnabled` (set on the layer/context) controls pattern
2016
+ // smoothing in the browser. node-canvas ignores it for pattern fills and
2017
+ // instead exposes a non-standard `patternQuality` property, so mirror the
2018
+ // current smoothing setting onto it to keep both backends consistent.
2019
+ const context = this._context;
2020
+ if ('patternQuality' in context) {
2021
+ context.patternQuality = context.imageSmoothingEnabled
2022
+ ? 'good'
2023
+ : 'nearest';
2024
+ }
1987
2025
  this.setAttr('fillStyle', shape._getFillPattern());
1988
2026
  shape._fillFunc(this);
1989
2027
  }
@@ -2245,6 +2283,14 @@ js: import "konva/skia-backend";
2245
2283
  this.setWidth(width || 0);
2246
2284
  this.setHeight(height || 0);
2247
2285
  }
2286
+ // setSize() re-allocates and clears the canvas even for the same size,
2287
+ // so lazily sized canvases use this to stay untouched when nothing changed
2288
+ setSizeIfChanged(width, height) {
2289
+ if (this.width !== width * this.pixelRatio ||
2290
+ this.height !== height * this.pixelRatio) {
2291
+ this.setSize(width, height);
2292
+ }
2293
+ }
2248
2294
  /**
2249
2295
  * to data url
2250
2296
  * @method
@@ -2310,13 +2356,36 @@ js: import "konva/skia-backend";
2310
2356
  return node;
2311
2357
  },
2312
2358
  _dragElements: new Map(),
2359
+ // Konva is imported into one window, but a stage may be rendered in another
2360
+ // one: an iframe, or a window opened with `window.open`. Such a window sends
2361
+ // its pointer events to itself, so `Konva.Stage` asks for every window it is
2362
+ // rendered in. The handlers get the window they listen to, as only that
2363
+ // window has pointer positions the stages of that window can use
2364
+ _listenToWindow(win) {
2365
+ const endDragBefore = (evt) => DD._endDragBefore(evt, win);
2366
+ const drag = (evt) => DD._drag(evt, win);
2367
+ win.addEventListener('mouseup', endDragBefore, true);
2368
+ win.addEventListener('touchend', endDragBefore, true);
2369
+ // add touchcancel to fix this: https://github.com/konvajs/konva/issues/1843
2370
+ win.addEventListener('touchcancel', endDragBefore, true);
2371
+ win.addEventListener('mousemove', drag);
2372
+ win.addEventListener('touchmove', drag);
2373
+ win.addEventListener('mouseup', DD._endDragAfter, false);
2374
+ win.addEventListener('touchend', DD._endDragAfter, false);
2375
+ win.addEventListener('touchcancel', DD._endDragAfter, false);
2376
+ },
2313
2377
  // methods
2314
- _drag(evt) {
2378
+ _drag(evt, win) {
2315
2379
  const nodesToFireEvents = [];
2316
2380
  DD._dragElements.forEach((elem, key) => {
2317
2381
  const { node } = elem;
2318
2382
  // we need to find pointer relative to that node
2319
2383
  const stage = node.getStage();
2384
+ // a pointer position of another window is relative to another viewport,
2385
+ // it would drag the node to a random place
2386
+ if (win && stage._getOwnerWindow() !== win) {
2387
+ return;
2388
+ }
2320
2389
  stage.setPointersPositions(evt);
2321
2390
  // it is possible that user call startDrag without any event
2322
2391
  // it that case we need to detect first movable pointer and attach it into the node
@@ -2358,13 +2427,15 @@ js: import "konva/skia-backend";
2358
2427
  },
2359
2428
  // dragBefore and dragAfter allows us to set correct order of events
2360
2429
  // setup all in dragbefore, and stop dragging only after pointerup triggered.
2361
- _endDragBefore(evt) {
2430
+ _endDragBefore(evt, win) {
2362
2431
  const drawNodes = [];
2363
2432
  DD._dragElements.forEach((elem) => {
2364
2433
  const { node } = elem;
2365
2434
  // we need to find pointer relative to that node
2366
2435
  const stage = node.getStage();
2367
- if (evt) {
2436
+ // a pointer released in another window ends the drag too - the pointer
2437
+ // is up everywhere - but its position is not used for this stage
2438
+ if (evt && (!win || stage._getOwnerWindow() === win)) {
2368
2439
  stage.setPointersPositions(evt);
2369
2440
  }
2370
2441
  const pos = stage._changedPointerPositions.find((pos) => pos.id === elem.pointerId);
@@ -2377,6 +2448,9 @@ js: import "konva/skia-backend";
2377
2448
  DD.justDragged = true;
2378
2449
  Konva$2._mouseListenClick = false;
2379
2450
  Konva$2._touchListenClick = false;
2451
+ // for real pointer input this reset comes too late — "pointerup" fired
2452
+ // before this handler — so Stage._pointerup also checks the live drag
2453
+ // state for the pointer family (issue #1756)
2380
2454
  Konva$2._pointerListenClick = false;
2381
2455
  elem.dragStatus = 'stopped';
2382
2456
  }
@@ -2408,17 +2482,6 @@ js: import "konva/skia-backend";
2408
2482
  });
2409
2483
  },
2410
2484
  };
2411
- if (Konva$2.isBrowser) {
2412
- window.addEventListener('mouseup', DD._endDragBefore, true);
2413
- window.addEventListener('touchend', DD._endDragBefore, true);
2414
- // add touchcancel to fix this: https://github.com/konvajs/konva/issues/1843
2415
- window.addEventListener('touchcancel', DD._endDragBefore, true);
2416
- window.addEventListener('mousemove', DD._drag);
2417
- window.addEventListener('touchmove', DD._drag);
2418
- window.addEventListener('mouseup', DD._endDragAfter, false);
2419
- window.addEventListener('touchend', DD._endDragAfter, false);
2420
- window.addEventListener('touchcancel', DD._endDragAfter, false);
2421
- }
2422
2485
 
2423
2486
  function _formatValue(val) {
2424
2487
  if (Util._isString(val)) {
@@ -2904,6 +2967,14 @@ js: import "konva/skia-backend";
2904
2967
  this.fire('absoluteTransformChange');
2905
2968
  }
2906
2969
  }
2970
+ static _runAfterAbsTransformCascade(cb) {
2971
+ if (Node._absTransformCascadeDepth > 0) {
2972
+ Node._pendingAfterCascade.push(cb);
2973
+ }
2974
+ else {
2975
+ cb();
2976
+ }
2977
+ }
2907
2978
  /**
2908
2979
  * clear cached canvas
2909
2980
  * @method
@@ -2915,7 +2986,7 @@ js: import "konva/skia-backend";
2915
2986
  clearCache() {
2916
2987
  if (this._cache.has(CANVAS)) {
2917
2988
  const { scene, filter, hit } = this._cache.get(CANVAS);
2918
- Util.releaseCanvas(scene._canvas, filter._canvas, hit._canvas);
2989
+ Util.releaseCanvas(scene._canvas, filter._canvas, ...(hit ? [hit._canvas] : []));
2919
2990
  this._cache.delete(CANVAS);
2920
2991
  }
2921
2992
  this._clearSelfAndDescendantCache();
@@ -3012,11 +3083,7 @@ js: import "konva/skia-backend";
3012
3083
  width: 0,
3013
3084
  height: 0,
3014
3085
  willReadFrequently: true,
3015
- }), cachedHitCanvas = new HitCanvas({
3016
- pixelRatio: hitCanvasPixelRatio,
3017
- width: width,
3018
- height: height,
3019
- }), sceneContext = cachedSceneCanvas.getContext(), hitContext = cachedHitCanvas.getContext();
3086
+ }), sceneContext = cachedSceneCanvas.getContext();
3020
3087
  const bufferCanvas = new SceneCanvas({
3021
3088
  // width and height already multiplied by pixelRatio
3022
3089
  // so we need to revert that
@@ -3025,7 +3092,6 @@ js: import "konva/skia-backend";
3025
3092
  height: cachedSceneCanvas.height / cachedSceneCanvas.pixelRatio + Math.abs(y),
3026
3093
  pixelRatio: cachedSceneCanvas.pixelRatio,
3027
3094
  }), bufferContext = bufferCanvas.getContext();
3028
- cachedHitCanvas.isCache = true;
3029
3095
  cachedSceneCanvas.isCache = true;
3030
3096
  this._cache.delete(CANVAS);
3031
3097
  this._filterUpToDate = false;
@@ -3034,10 +3100,8 @@ js: import "konva/skia-backend";
3034
3100
  cachedFilterCanvas.getContext()._context.imageSmoothingEnabled = false;
3035
3101
  }
3036
3102
  sceneContext.save();
3037
- hitContext.save();
3038
3103
  bufferContext.save();
3039
3104
  sceneContext.translate(-x, -y);
3040
- hitContext.translate(-x, -y);
3041
3105
  bufferContext.translate(-x, -y);
3042
3106
  // hard-code offset to make sure content fits canvas
3043
3107
  // @ts-ignore
@@ -3049,10 +3113,8 @@ js: import "konva/skia-backend";
3049
3113
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
3050
3114
  this._clearSelfAndDescendantCache(ABSOLUTE_SCALE);
3051
3115
  this.drawScene(cachedSceneCanvas, this, bufferCanvas);
3052
- this.drawHit(cachedHitCanvas, this);
3053
3116
  this._isUnderCache = false;
3054
3117
  sceneContext.restore();
3055
- hitContext.restore();
3056
3118
  // this will draw a red border around the cached box for
3057
3119
  // debugging purposes
3058
3120
  if (drawBorder) {
@@ -3071,13 +3133,46 @@ js: import "konva/skia-backend";
3071
3133
  this._cache.set(CANVAS, {
3072
3134
  scene: cachedSceneCanvas,
3073
3135
  filter: cachedFilterCanvas,
3074
- hit: cachedHitCanvas,
3136
+ // the hit canvas is built on demand (see _getCachedHitCanvas)
3137
+ hit: null,
3138
+ hitConfig: {
3139
+ pixelRatio: hitCanvasPixelRatio,
3140
+ width: width,
3141
+ height: height,
3142
+ },
3075
3143
  x: x,
3076
3144
  y: y,
3077
3145
  });
3078
3146
  this._requestDraw();
3079
3147
  return this;
3080
3148
  }
3149
+ // build the hit canvas of a cached node lazily - only when the hit graph
3150
+ // is actually needed, so a non-listening node never allocates it
3151
+ // https://github.com/konvajs/konva/issues/2009
3152
+ _getCachedHitCanvas(top) {
3153
+ // top === this means the node is drawing into its own cache right now:
3154
+ // the build below re-enters drawHit for this very node, and consulting
3155
+ // the not-yet-stored canvas again would recurse forever
3156
+ if (top === this) {
3157
+ return null;
3158
+ }
3159
+ const cache = this._getCanvasCache();
3160
+ if (!cache) {
3161
+ return null;
3162
+ }
3163
+ if (cache.hit) {
3164
+ return cache.hit;
3165
+ }
3166
+ const hitCanvas = new HitCanvas(cache.hitConfig);
3167
+ hitCanvas.isCache = true;
3168
+ const hitContext = hitCanvas.getContext();
3169
+ hitContext.save();
3170
+ hitContext.translate(-cache.x, -cache.y);
3171
+ this.drawHit(hitCanvas, this);
3172
+ hitContext.restore();
3173
+ cache.hit = hitCanvas;
3174
+ return hitCanvas;
3175
+ }
3081
3176
  /**
3082
3177
  * determine if node is currently cached
3083
3178
  * @method
@@ -3166,8 +3261,8 @@ js: import "konva/skia-backend";
3166
3261
  context.drawImage(cacheCanvas._canvas, 0, 0, cacheCanvas.width / ratio, cacheCanvas.height / ratio);
3167
3262
  context.restore();
3168
3263
  }
3169
- _drawCachedHitCanvas(context) {
3170
- const canvasCache = this._getCanvasCache(), hitCanvas = canvasCache.hit;
3264
+ _drawCachedHitCanvas(context, hitCanvas) {
3265
+ const canvasCache = this._getCanvasCache();
3171
3266
  context.save();
3172
3267
  context.translate(canvasCache.x, canvasCache.y);
3173
3268
  context.drawImage(hitCanvas._canvas, 0, 0, hitCanvas.width / hitCanvas.pixelRatio, hitCanvas.height / hitCanvas.pixelRatio);
@@ -3224,6 +3319,67 @@ js: import "konva/skia-backend";
3224
3319
  this._filterUpToDate = true;
3225
3320
  return filterCanvas;
3226
3321
  }
3322
+ /**
3323
+ * bind events to the node. KonvaJS supports mouseover, mousemove,
3324
+ * mouseout, mouseenter, mouseleave, mousedown, mouseup, wheel, contextmenu, click, dblclick, touchstart, touchmove,
3325
+ * touchend, tap, dbltap, dragstart, dragmove, and dragend events.
3326
+ * Pass in a string of events delimited by a space to bind multiple events at once
3327
+ * such as 'mousedown mouseup mousemove'. Include a namespace to bind an
3328
+ * event by name such as 'click.foobar'.
3329
+ * @method
3330
+ * @name Konva.Node#on
3331
+ * @param {String} evtStr e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo'
3332
+ * @param {Function} handler The handler function. The first argument of that function is event object. Event object has `target` as main target of the event, `currentTarget` as current node listener and `evt` as native browser event.
3333
+ * @returns {Konva.Node}
3334
+ * @example
3335
+ * // add click listener
3336
+ * node.on('click', function() {
3337
+ * console.log('you clicked me!');
3338
+ * });
3339
+ *
3340
+ * // get the target node
3341
+ * node.on('click', function(evt) {
3342
+ * console.log(evt.target);
3343
+ * });
3344
+ *
3345
+ * // stop event propagation
3346
+ * node.on('click', function(evt) {
3347
+ * evt.cancelBubble = true;
3348
+ * });
3349
+ *
3350
+ * // bind multiple listeners
3351
+ * node.on('click touchstart', function() {
3352
+ * console.log('you clicked/touched me!');
3353
+ * });
3354
+ *
3355
+ * // namespace listener
3356
+ * node.on('click.foo', function() {
3357
+ * console.log('you clicked/touched me!');
3358
+ * });
3359
+ *
3360
+ * // get the event type
3361
+ * node.on('click tap', function(evt) {
3362
+ * var eventType = evt.type;
3363
+ * });
3364
+ *
3365
+ * // get native event object
3366
+ * node.on('click tap', function(evt) {
3367
+ * var nativeEvent = evt.evt;
3368
+ * });
3369
+ *
3370
+ * // for change events, get the old and new val
3371
+ * node.on('xChange', function(evt) {
3372
+ * var oldVal = evt.oldVal;
3373
+ * var newVal = evt.newVal;
3374
+ * });
3375
+ *
3376
+ * // get event targets
3377
+ * // with event delegations
3378
+ * layer.on('click', 'Group', function(evt) {
3379
+ * var shape = evt.target;
3380
+ * var group = evt.currentTarget;
3381
+ * });
3382
+ */
3227
3383
  on(...args) {
3228
3384
  const evtStr = args[0];
3229
3385
  const selectorOrHandler = args[1];
@@ -3684,7 +3840,7 @@ js: import "konva/skia-backend";
3684
3840
  * get absolute position of a node. That function can be used to calculate absolute position, but relative to any ancestor
3685
3841
  * @method
3686
3842
  * @name Konva.Node#getAbsolutePosition
3687
- * @param {Object} Ancestor optional ancestor node
3843
+ * @param {Object} [top] optional ancestor node
3688
3844
  * @returns {Konva.Node}
3689
3845
  * @example
3690
3846
  *
@@ -4743,10 +4899,20 @@ js: import "konva/skia-backend";
4743
4899
  if (events === undefined) {
4744
4900
  //recalculate cache
4745
4901
  events = [];
4902
+ // Dedupe across the prototype chain: subclasses without their own
4903
+ // `eventListeners` inherit the parent's, so a single handler would
4904
+ // otherwise be pushed once per chain level (Stage→Container→Node = 3x).
4905
+ const seen = new Set();
4746
4906
  let obj = Object.getPrototypeOf(this);
4747
4907
  while (obj) {
4748
4908
  const hierarchyEvents = (_b = (_a = obj.eventListeners) === null || _a === void 0 ? void 0 : _a[eventType]) !== null && _b !== void 0 ? _b : [];
4749
- events.push(...hierarchyEvents);
4909
+ for (let i = 0; i < hierarchyEvents.length; i++) {
4910
+ const entry = hierarchyEvents[i];
4911
+ if (!seen.has(entry)) {
4912
+ seen.add(entry);
4913
+ events.push(entry);
4914
+ }
4915
+ }
4750
4916
  obj = Object.getPrototypeOf(obj);
4751
4917
  }
4752
4918
  // update cache
@@ -4761,9 +4927,10 @@ js: import "konva/skia-backend";
4761
4927
  evt.type = eventType;
4762
4928
  const topListeners = this._getProtoListeners(eventType);
4763
4929
  if (topListeners) {
4764
- const list = topListeners.slice();
4765
- for (let i = 0; i < list.length; i++) {
4766
- list[i].handler.call(this, evt);
4930
+ // Proto listeners are wired at module load and never mutated at
4931
+ // runtime, so no defensive .slice() needed (hot path: every *Change).
4932
+ for (let i = 0; i < topListeners.length; i++) {
4933
+ topListeners[i].handler.call(this, evt);
4767
4934
  }
4768
4935
  }
4769
4936
  // snapshot prevents skipping listeners when a handler mutates the array
@@ -4985,7 +5152,7 @@ js: import "konva/skia-backend";
4985
5152
  * and setImage() methods
4986
5153
  * @method
4987
5154
  * @memberof Konva.Node
4988
- * @param {String|Object} json string or object
5155
+ * @param {String|Object} data string or object
4989
5156
  * @param {Element} [container] optional container dom element used only if you're
4990
5157
  * creating a stage node
4991
5158
  */
@@ -5018,6 +5185,12 @@ js: import "konva/skia-backend";
5018
5185
  return no;
5019
5186
  }
5020
5187
  }
5188
+ // Perf: lets a listener inside an absoluteTransform cascade (e.g. Konva
5189
+ // .Transformer reacting to a stage drag fan-out across N attached nodes)
5190
+ // defer work until the cascade ends — collapses O(N) listener-driven calls
5191
+ // into one. Counter is mutated by Container's _clearSelfAndDescendantCache.
5192
+ Node._absTransformCascadeDepth = 0;
5193
+ Node._pendingAfterCascade = [];
5021
5194
  Node.protoListenerMap = new Map();
5022
5195
  Node.prototype.nodeType = 'Node';
5023
5196
  Node.prototype._attrsAffectingSize = [];
@@ -5389,6 +5562,8 @@ js: import "konva/skia-backend";
5389
5562
  * by taking into account its parents, use the isListening() method
5390
5563
  * nodes with listening set to false will not be detected in hit graph
5391
5564
  * so they will be ignored in container.getIntersection() method
5565
+ * a non-listening layer (or a layer of a non-listening stage) also
5566
+ * releases its hit canvas, so it uses less memory
5392
5567
  * @name Konva.Node#listening
5393
5568
  * @method
5394
5569
  * @param {Boolean} listening Can be true, or false. The default is true.
@@ -5863,15 +6038,31 @@ js: import "konva/skia-backend";
5863
6038
  }
5864
6039
  _clearSelfAndDescendantCache(attr) {
5865
6040
  var _a;
5866
- super._clearSelfAndDescendantCache(attr);
5867
- // skip clearing if node is cached with canvas
5868
- // for performance reasons !!!
5869
- if (this.isCached()) {
5870
- return;
6041
+ // Perf: bracket absoluteTransform cascades with a depth counter so
6042
+ // Node._runAfterAbsTransformCascade can defer work until the outermost
6043
+ // walk returns. try/finally so depth/flush survive listener exceptions.
6044
+ const isAbsTransform = attr === 'absoluteTransform';
6045
+ if (isAbsTransform)
6046
+ Node._absTransformCascadeDepth++;
6047
+ try {
6048
+ super._clearSelfAndDescendantCache(attr);
6049
+ // skip clearing if node is cached with canvas (perf)
6050
+ if (this.isCached())
6051
+ return;
6052
+ (_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (node) {
6053
+ node._clearSelfAndDescendantCache(attr);
6054
+ });
6055
+ }
6056
+ finally {
6057
+ if (isAbsTransform && --Node._absTransformCascadeDepth === 0) {
6058
+ const callbacks = Node._pendingAfterCascade;
6059
+ if (callbacks.length) {
6060
+ Node._pendingAfterCascade = [];
6061
+ for (let i = 0; i < callbacks.length; i++)
6062
+ callbacks[i]();
6063
+ }
6064
+ }
5871
6065
  }
5872
- (_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (node) {
5873
- node._clearSelfAndDescendantCache(attr);
5874
- });
5875
6066
  }
5876
6067
  _setChildrenIndices() {
5877
6068
  var _a;
@@ -5902,12 +6093,12 @@ js: import "konva/skia-backend";
5902
6093
  if (!this.shouldDrawHit(top)) {
5903
6094
  return this;
5904
6095
  }
5905
- const layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas), context = canvas && canvas.getContext(), cachedCanvas = this._getCanvasCache(), cachedHitCanvas = cachedCanvas && cachedCanvas.hit;
6096
+ const layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas), context = canvas && canvas.getContext(), cachedHitCanvas = this._getCachedHitCanvas(top);
5906
6097
  if (cachedHitCanvas) {
5907
6098
  context.save();
5908
6099
  const m = this.getAbsoluteTransform(top).getMatrix();
5909
6100
  context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
5910
- this._drawCachedHitCanvas(context);
6101
+ this._drawCachedHitCanvas(context, cachedHitCanvas);
5911
6102
  context.restore();
5912
6103
  }
5913
6104
  else {
@@ -6152,23 +6343,41 @@ js: import "konva/skia-backend";
6152
6343
  return Captures.get(pointerId) === shape;
6153
6344
  }
6154
6345
  function setPointerCapture(pointerId, shape) {
6346
+ var _a;
6155
6347
  releaseCapture(pointerId);
6156
6348
  const stage = shape.getStage();
6157
6349
  if (!stage)
6158
6350
  return;
6159
6351
  Captures.set(pointerId, shape);
6160
6352
  if (SUPPORT_POINTER_EVENTS) {
6353
+ // capture on the DOM level too, so the stage keeps receiving the events
6354
+ // of that pointer even when it moves outside of the stage container
6355
+ // https://github.com/konvajs/konva/issues/1992
6356
+ try {
6357
+ (_a = stage.content) === null || _a === void 0 ? void 0 : _a.setPointerCapture(pointerId);
6358
+ }
6359
+ catch (e) {
6360
+ // capture is possible only for an active pointer;
6361
+ // ids of mouse and touch events (999 and touch identifiers) and
6362
+ // programmatic calls outside of a pointer event land here
6363
+ }
6161
6364
  shape._fire('gotpointercapture', createEvent(new PointerEvent('gotpointercapture')));
6162
6365
  }
6163
6366
  }
6164
6367
  function releaseCapture(pointerId, target) {
6368
+ var _a;
6165
6369
  const shape = Captures.get(pointerId);
6166
6370
  if (!shape)
6167
6371
  return;
6168
6372
  const stage = shape.getStage();
6169
- if (stage && stage.content) ;
6170
6373
  Captures.delete(pointerId);
6171
6374
  if (SUPPORT_POINTER_EVENTS) {
6375
+ try {
6376
+ (_a = stage === null || stage === void 0 ? void 0 : stage.content) === null || _a === void 0 ? void 0 : _a.releasePointerCapture(pointerId);
6377
+ }
6378
+ catch (e) {
6379
+ // same as in setPointerCapture: the pointer may not be active
6380
+ }
6172
6381
  shape._fire('lostpointercapture', createEvent(new PointerEvent('lostpointercapture')));
6173
6382
  }
6174
6383
  }
@@ -6261,6 +6470,27 @@ js: import "konva/skia-backend";
6261
6470
  }
6262
6471
  const NO_POINTERS_MESSAGE = `Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);`;
6263
6472
  const stages = [];
6473
+ // A stage may be rendered in another window than the one Konva was imported
6474
+ // into: an iframe, or a window opened with `window.open`. Such a window sends
6475
+ // its own events and has its own visibility state, so Konva listens to every
6476
+ // window it renders a stage in
6477
+ const listeningWindows = new WeakSet();
6478
+ const listenToWindow = (win) => {
6479
+ if (!win || listeningWindows.has(win)) {
6480
+ return;
6481
+ }
6482
+ listeningWindows.add(win);
6483
+ DD._listenToWindow(win);
6484
+ // chrome is clearing canvas in inactive browser window, causing layer content to be erased
6485
+ // so let's redraw layers as soon as window becomes active
6486
+ // TODO: any other way to solve this issue?
6487
+ // TODO: should we remove it if chrome fixes the issue?
6488
+ win.document.addEventListener('visibilitychange', () => {
6489
+ stages.forEach((stage) => {
6490
+ stage.batchDraw();
6491
+ });
6492
+ });
6493
+ };
6264
6494
  /**
6265
6495
  * Stage constructor. A stage is used to contain multiple layers
6266
6496
  * @constructor
@@ -6325,6 +6555,18 @@ js: import "konva/skia-backend";
6325
6555
  const style = this.visible() ? '' : 'none';
6326
6556
  this.content.style.display = style;
6327
6557
  }
6558
+ /**
6559
+ * The window the stage is rendered in. It is not always the window Konva was
6560
+ * imported into: the container may belong to an iframe, or to a window
6561
+ * opened with `window.open`.
6562
+ */
6563
+ _getOwnerWindow() {
6564
+ var _a;
6565
+ const element = this.content || this.container();
6566
+ // a document with no browsing context, such as one of `DOMParser`, has no
6567
+ // window of its own. The window Konva was imported into is used then
6568
+ return (((_a = element === null || element === void 0 ? void 0 : element.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) || (Konva$2.isBrowser ? window : null));
6569
+ }
6328
6570
  /**
6329
6571
  * set container dom element which contains the stage wrapper div element
6330
6572
  * @method
@@ -6357,6 +6599,8 @@ js: import "konva/skia-backend";
6357
6599
  this.content.parentElement.removeChild(this.content);
6358
6600
  }
6359
6601
  container.appendChild(this.content);
6602
+ // the new container may be in another window, with its own events
6603
+ listenToWindow(this._getOwnerWindow());
6360
6604
  }
6361
6605
  return this;
6362
6606
  }
@@ -6486,14 +6730,19 @@ js: import "konva/skia-backend";
6486
6730
  this.content.style.width = width + PX;
6487
6731
  this.content.style.height = height + PX;
6488
6732
  }
6489
- this.bufferCanvas.setSize(width, height);
6490
- this.bufferHitCanvas.setSize(width, height);
6491
6733
  // set layer dimensions
6492
6734
  this.children.forEach((layer) => {
6493
6735
  layer.setSize({ width, height });
6494
6736
  layer.draw();
6495
6737
  });
6496
6738
  }
6739
+ // "perfect drawing" uses bufferCanvas, shape.intersects() uses
6740
+ // bufferHitCanvas; both are lazy - created at 0x0 and sized to the stage
6741
+ // on first use
6742
+ _syncBufferSize(canvas) {
6743
+ canvas.setSizeIfChanged(this.width(), this.height());
6744
+ return canvas;
6745
+ }
6497
6746
  add(layer, ...rest) {
6498
6747
  if (arguments.length > 1) {
6499
6748
  for (let i = 0; i < arguments.length; i++) {
@@ -6735,6 +6984,13 @@ js: import "konva/skia-backend";
6735
6984
  return;
6736
6985
  }
6737
6986
  this.setPointersPositions(evt);
6987
+ // the mouse/touch families get their "listen click" flags reset by
6988
+ // DD._endDragBefore, but native "pointerup" fires before the
6989
+ // "mouseup"/"touchend" that ends the drag, so for the pointer family the
6990
+ // flags are still set — check the live drag state as well, otherwise
6991
+ // "pointerclick" fires after a drag while "click" does not (issue #1756)
6992
+ const wasDragged = DD.justDragged || (eventType === 'pointer' && Konva$2.isDragging());
6993
+ const listenClick = Konva$2['_' + eventType + 'ListenClick'] && !wasDragged;
6738
6994
  const clickStartShape = this[eventType + 'ClickStartShape'];
6739
6995
  const clickEndShape = this[eventType + 'ClickEndShape'];
6740
6996
  const processedShapesIds = {};
@@ -6756,7 +7012,7 @@ js: import "konva/skia-backend";
6756
7012
  fireDblClick = true;
6757
7013
  clearTimeout(this[eventType + 'DblTimeout']);
6758
7014
  }
6759
- else if (!DD.justDragged) {
7015
+ else if (!wasDragged) {
6760
7016
  // don't set inDblClickWindow after dragging
6761
7017
  Konva$2['_' + eventType + 'InDblClickWindow'] = true;
6762
7018
  clearTimeout(this[eventType + 'DblTimeout']);
@@ -6769,9 +7025,7 @@ js: import "konva/skia-backend";
6769
7025
  this[eventType + 'ClickEndShape'] = shape;
6770
7026
  shape._fireAndBubble(events.pointerup, { ...event });
6771
7027
  // detect if click or double click occurred
6772
- if (Konva$2['_' + eventType + 'ListenClick'] &&
6773
- clickStartShape &&
6774
- clickStartShape === shape) {
7028
+ if (listenClick && clickStartShape === shape) {
6775
7029
  shape._fireAndBubble(events.pointerclick, { ...event });
6776
7030
  if (fireDblClick && clickEndShape && clickEndShape === shape) {
6777
7031
  shape._fireAndBubble(events.pointerdblclick, { ...event });
@@ -6789,7 +7043,7 @@ js: import "konva/skia-backend";
6789
7043
  });
6790
7044
  skipPointerUpTrigger = true;
6791
7045
  }
6792
- if (Konva$2['_' + eventType + 'ListenClick']) {
7046
+ if (listenClick) {
6793
7047
  this._fire(events.pointerclick, {
6794
7048
  evt: evt,
6795
7049
  target: this,
@@ -6872,7 +7126,7 @@ js: import "konva/skia-backend";
6872
7126
  * is triggered outside of the stage, but you still want to use Konva methods to get pointers position.
6873
7127
  * @method
6874
7128
  * @name Konva.Stage#setPointersPositions
6875
- * @param {Object} event Event object
7129
+ * @param {Object} evt Event object
6876
7130
  * @example
6877
7131
  *
6878
7132
  * window.addEventListener('mousemove', (e) => {
@@ -6942,14 +7196,16 @@ js: import "konva/skia-backend";
6942
7196
  };
6943
7197
  }
6944
7198
  _buildDOM() {
7199
+ // lazy buffer canvases, see _syncBufferSize
7200
+ // https://github.com/konvajs/konva/issues/2009
6945
7201
  this.bufferCanvas = new SceneCanvas({
6946
- width: this.width(),
6947
- height: this.height(),
7202
+ width: 0,
7203
+ height: 0,
6948
7204
  });
6949
7205
  this.bufferHitCanvas = new HitCanvas({
6950
7206
  pixelRatio: 1,
6951
- width: this.width(),
6952
- height: this.height(),
7207
+ width: 0,
7208
+ height: 0,
6953
7209
  });
6954
7210
  if (!Konva$2.isBrowser) {
6955
7211
  return;
@@ -6961,12 +7217,15 @@ js: import "konva/skia-backend";
6961
7217
  // clear content inside container
6962
7218
  container.innerHTML = '';
6963
7219
  // content
6964
- this.content = document.createElement('div');
7220
+ // the container may belong to another document - an iframe, or a popout
7221
+ // window - so the content is created in the document of the container
7222
+ this.content = container.ownerDocument.createElement('div');
6965
7223
  this.content.style.position = 'relative';
6966
7224
  this.content.style.userSelect = 'none';
6967
7225
  this.content.className = 'konvajs-content';
6968
7226
  this.content.setAttribute('role', 'presentation');
6969
7227
  container.appendChild(this.content);
7228
+ listenToWindow(this._getOwnerWindow());
6970
7229
  this._resizeDOM();
6971
7230
  }
6972
7231
  // currently cache function is now working for stage, because stage has no its own canvas element
@@ -6993,7 +7252,9 @@ js: import "konva/skia-backend";
6993
7252
  Stage.prototype.nodeType = STAGE;
6994
7253
  _registerNode(Stage);
6995
7254
  /**
6996
- * get/set container DOM element
7255
+ * get/set container DOM element. The container may belong to another window
7256
+ * than the one Konva was imported into: an iframe, or a window opened with
7257
+ * `window.open`. The stage then uses the events and the frames of that window.
6997
7258
  * @method
6998
7259
  * @name Konva.Stage#container
6999
7260
  * @returns {DomElement} container
@@ -7004,19 +7265,12 @@ js: import "konva/skia-backend";
7004
7265
  * var container = document.createElement('div');
7005
7266
  * body.appendChild(container);
7006
7267
  * stage.container(container);
7268
+ *
7269
+ * // a stage in a popout window
7270
+ * var popout = window.open('', '', 'width=600,height=400');
7271
+ * stage.container(popout.document.body);
7007
7272
  */
7008
7273
  Factory.addGetterSetter(Stage, 'container');
7009
- // chrome is clearing canvas in inactive browser window, causing layer content to be erased
7010
- // so let's redraw layers as soon as window becomes active
7011
- // TODO: any other way to solve this issue?
7012
- // TODO: should we remove it if chrome fixes the issue?
7013
- if (Konva$2.isBrowser) {
7014
- document.addEventListener('visibilitychange', () => {
7015
- stages.forEach((stage) => {
7016
- stage.batchDraw();
7017
- });
7018
- });
7019
- }
7020
7274
 
7021
7275
  const HAS_SHADOW = 'hasShadow';
7022
7276
  const SHADOW_RGBA = 'shadowRGBA';
@@ -7389,7 +7643,7 @@ js: import "konva/skia-backend";
7389
7643
  if (!stage) {
7390
7644
  return false;
7391
7645
  }
7392
- const bufferHitCanvas = stage.bufferHitCanvas;
7646
+ const bufferHitCanvas = stage._syncBufferSize(stage.bufferHitCanvas);
7393
7647
  bufferHitCanvas.getContext().clear();
7394
7648
  this.drawHit(bufferHitCanvas, undefined, true);
7395
7649
  const p = bufferHitCanvas.context.getImageData(Math.round(point.x), Math.round(point.y), 1, 1).data;
@@ -7536,7 +7790,7 @@ js: import "konva/skia-backend";
7536
7790
  // if buffer canvas is needed
7537
7791
  if (this._useBufferCanvas() && true) {
7538
7792
  stage = this.getStage();
7539
- const bc = bufferCanvas || stage.bufferCanvas;
7793
+ const bc = bufferCanvas || stage._syncBufferSize(stage.bufferCanvas);
7540
7794
  const bufferContext = bc.getContext();
7541
7795
  // When caching, the buffer canvas may have a translation applied.
7542
7796
  // We need to reset the transform before clearing to ensure the entire canvas is cleared.
@@ -7550,6 +7804,10 @@ js: import "konva/skia-backend";
7550
7804
  bufferContext.clear();
7551
7805
  }
7552
7806
  bufferContext.save();
7807
+ // the buffer canvas is a separate context that does not inherit the
7808
+ // destination `imageSmoothingEnabled` flag, so propagate it to keep
7809
+ // pattern/image smoothing consistent with the target context.
7810
+ bufferContext.imageSmoothingEnabled = context.imageSmoothingEnabled;
7553
7811
  bufferContext._applyLineJoin(this);
7554
7812
  bufferContext._applyMiterLimit(this);
7555
7813
  // layer might be undefined if we are using cache before adding to layer
@@ -7599,7 +7857,7 @@ js: import "konva/skia-backend";
7599
7857
  if (!this.shouldDrawHit(top, skipDragCheck)) {
7600
7858
  return this;
7601
7859
  }
7602
- const layer = this.getLayer(), canvas = can || layer.hitCanvas, context = canvas && canvas.getContext(), drawFunc = this.hitFunc() || this.sceneFunc(), cachedCanvas = this._getCanvasCache(), cachedHitCanvas = cachedCanvas && cachedCanvas.hit;
7860
+ const layer = this.getLayer(), canvas = can || layer.hitCanvas, context = canvas && canvas.getContext(), drawFunc = this.hitFunc() || this.sceneFunc(), cachedHitCanvas = this._getCachedHitCanvas(top);
7603
7861
  if (!this.colorKey) {
7604
7862
  Util.warn('Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()');
7605
7863
  }
@@ -7607,7 +7865,7 @@ js: import "konva/skia-backend";
7607
7865
  context.save();
7608
7866
  const m = this.getAbsoluteTransform(top).getMatrix();
7609
7867
  context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
7610
- this._drawCachedHitCanvas(context);
7868
+ this._drawCachedHitCanvas(context, cachedHitCanvas);
7611
7869
  context.restore();
7612
7870
  return this;
7613
7871
  }
@@ -7639,7 +7897,7 @@ js: import "konva/skia-backend";
7639
7897
  * shape.drawHitFromCache();
7640
7898
  */
7641
7899
  drawHitFromCache(alphaThreshold = 0) {
7642
- const cachedCanvas = this._getCanvasCache(), sceneCanvas = this._getCachedSceneCanvas(), hitCanvas = cachedCanvas.hit, hitContext = hitCanvas.getContext(), hitWidth = hitCanvas.getWidth(), hitHeight = hitCanvas.getHeight();
7900
+ const sceneCanvas = this._getCachedSceneCanvas(), hitCanvas = this._getCachedHitCanvas(), hitContext = hitCanvas.getContext(), hitWidth = hitCanvas.getWidth(), hitHeight = hitCanvas.getHeight();
7643
7901
  hitContext.clear();
7644
7902
  hitContext.drawImage(sceneCanvas._canvas, 0, 0, hitWidth, hitHeight);
7645
7903
  try {
@@ -8917,10 +9175,18 @@ js: import "konva/skia-backend";
8917
9175
  }
8918
9176
  setSize({ width, height }) {
8919
9177
  this.canvas.setSize(width, height);
8920
- this.hitCanvas.setSize(width, height);
9178
+ this._syncHitCanvasSize();
8921
9179
  this._setSmoothEnabled();
8922
9180
  return this;
8923
9181
  }
9182
+ // the hit canvas is only allocated while the layer is listening;
9183
+ // for a non-listening layer it is kept released (0x0), so a purely
9184
+ // presentational layer does not pay for a stage-sized hit bitmap
9185
+ // https://github.com/konvajs/konva/issues/2009
9186
+ _syncHitCanvasSize() {
9187
+ const listening = this.isListening();
9188
+ this.hitCanvas.setSizeIfChanged((listening ? this.getWidth() : 0) || 0, (listening ? this.getHeight() : 0) || 0);
9189
+ }
8924
9190
  _validateAdd(child) {
8925
9191
  const type = child.getType();
8926
9192
  if (type !== 'Group' && type !== 'Shape') {
@@ -8990,12 +9256,15 @@ js: import "konva/skia-backend";
8990
9256
  * @return {Konva.Layer} this
8991
9257
  */
8992
9258
  batchDraw() {
9259
+ var _a;
8993
9260
  if (!this._waitingForDraw) {
8994
9261
  this._waitingForDraw = true;
9262
+ // ask the window the stage is rendered in for the frame: a stage in a
9263
+ // popout window keeps drawing while the opener window is not visible
8995
9264
  Util.requestAnimFrame(() => {
8996
9265
  this.draw();
8997
9266
  this._waitingForDraw = false;
8998
- });
9267
+ }, (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._getOwnerWindow());
8999
9268
  }
9000
9269
  return this;
9001
9270
  }
@@ -9050,6 +9319,11 @@ js: import "konva/skia-backend";
9050
9319
  }
9051
9320
  }
9052
9321
  _getIntersection(pos) {
9322
+ // a non-listening layer keeps its hit canvas released (0x0),
9323
+ // and a just-enabled layer may not have drawn its hit graph yet
9324
+ if (!this.hitCanvas.width || !this.hitCanvas.height) {
9325
+ return {};
9326
+ }
9053
9327
  const ratio = this.hitCanvas.pixelRatio;
9054
9328
  const p = this.hitCanvas.context.getImageData(Math.round(pos.x * ratio), Math.round(pos.y * ratio), 1, 1).data;
9055
9329
  const p3 = p[3];
@@ -9091,8 +9365,13 @@ js: import "konva/skia-backend";
9091
9365
  }
9092
9366
  drawHit(can, top) {
9093
9367
  const layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas);
9094
- if (layer && layer.clearBeforeDraw()) {
9095
- layer.getHitCanvas().getContext().clear();
9368
+ if (!can && layer) {
9369
+ // allocate or release the hit canvas to match the current listening
9370
+ // state - this also picks up a listening change made after the last draw
9371
+ layer._syncHitCanvasSize();
9372
+ if (layer.clearBeforeDraw()) {
9373
+ layer.getHitCanvas().getContext().clear();
9374
+ }
9096
9375
  }
9097
9376
  Container.prototype.drawHit.call(this, canvas, top);
9098
9377
  return this;
@@ -9505,6 +9784,14 @@ js: import "konva/skia-backend";
9505
9784
  yoyo: 1,
9506
9785
  }, PAUSED = 1, PLAYING = 2, REVERSING = 3, colorAttrs = ['fill', 'stroke', 'shadowColor'];
9507
9786
  let idCounter = 0;
9787
+ // the diff below reads r/g/b/a directly, so a color we can not parse must fail
9788
+ // with its own message instead of "Cannot read properties of undefined"
9789
+ function colorToRGBA(color) {
9790
+ return (Util.colorToRGBA(color) ||
9791
+ Util.throw('can not tween the color "' +
9792
+ color +
9793
+ '", because it is not a valid color.'));
9794
+ }
9508
9795
  class TweenEngine {
9509
9796
  constructor(prop, propFunc, func, begin, finish, duration, yoyo) {
9510
9797
  this.prop = prop;
@@ -9728,8 +10015,8 @@ js: import "konva/skia-backend";
9728
10015
  diff.push(end[n] - start[n]);
9729
10016
  }
9730
10017
  else {
9731
- const startRGBA = Util.colorToRGBA(start[n]);
9732
- endRGBA = Util.colorToRGBA(end[n]);
10018
+ const startRGBA = colorToRGBA(start[n]);
10019
+ endRGBA = colorToRGBA(end[n]);
9733
10020
  start[n] = startRGBA;
9734
10021
  diff.push({
9735
10022
  r: endRGBA.r - startRGBA.r,
@@ -9747,8 +10034,8 @@ js: import "konva/skia-backend";
9747
10034
  }
9748
10035
  }
9749
10036
  else if (colorAttrs.indexOf(key) !== -1) {
9750
- start = Util.colorToRGBA(start);
9751
- endRGBA = Util.colorToRGBA(end);
10037
+ start = colorToRGBA(start);
10038
+ endRGBA = colorToRGBA(end);
9752
10039
  diff = {
9753
10040
  r: endRGBA.r - start.r,
9754
10041
  g: endRGBA.g - start.g,
@@ -10358,6 +10645,20 @@ js: import "konva/skia-backend";
10358
10645
  const innerRadius = this.innerRadius();
10359
10646
  const outerRadius = this.outerRadius();
10360
10647
  const clockwise = this.clockwise();
10648
+ // canvas draws a full circle for any non-zero full-turn end angle regardless
10649
+ // of direction, and nothing for angle 0. The 360 - angle flip below maps both
10650
+ // onto the same value, so handle exact full turns before the trig formula.
10651
+ const rawAngle = Konva$2.getAngle(this.angle());
10652
+ if (rawAngle % (Math.PI * 2) === 0) {
10653
+ return rawAngle !== 0
10654
+ ? {
10655
+ x: -outerRadius,
10656
+ y: -outerRadius,
10657
+ width: outerRadius * 2,
10658
+ height: outerRadius * 2,
10659
+ }
10660
+ : { x: innerRadius, y: 0, width: outerRadius - innerRadius, height: 0 };
10661
+ }
10361
10662
  const angle = Konva$2.getAngle(clockwise ? 360 - this.angle() : this.angle());
10362
10663
  const boundLeftRatio = Math.cos(Math.min(angle, Math.PI));
10363
10664
  const boundRightRatio = 1;
@@ -10445,357 +10746,6 @@ js: import "konva/skia-backend";
10445
10746
  * arc.clockwise(true);
10446
10747
  */
10447
10748
 
10448
- function getControlPoints(x0, y0, x1, y1, x2, y2, t) {
10449
- const d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)), d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), fa = (t * d01) / (d01 + d12), fb = (t * d12) / (d01 + d12), p1x = x1 - fa * (x2 - x0), p1y = y1 - fa * (y2 - y0), p2x = x1 + fb * (x2 - x0), p2y = y1 + fb * (y2 - y0);
10450
- return [p1x, p1y, p2x, p2y];
10451
- }
10452
- function expandPoints(p, tension) {
10453
- const len = p.length, allPoints = [];
10454
- for (let n = 2; n < len - 2; n += 2) {
10455
- const cp = getControlPoints(p[n - 2], p[n - 1], p[n], p[n + 1], p[n + 2], p[n + 3], tension);
10456
- if (isNaN(cp[0])) {
10457
- continue;
10458
- }
10459
- allPoints.push(cp[0]);
10460
- allPoints.push(cp[1]);
10461
- allPoints.push(p[n]);
10462
- allPoints.push(p[n + 1]);
10463
- allPoints.push(cp[2]);
10464
- allPoints.push(cp[3]);
10465
- }
10466
- return allPoints;
10467
- }
10468
- function getBezierExtremaPoints(points) {
10469
- const axisPoints = [
10470
- [points[0], points[2], points[4], points[6]],
10471
- [points[1], points[3], points[5], points[7]],
10472
- ];
10473
- const extremaTs = [];
10474
- for (const axis of axisPoints) {
10475
- const a = -3 * axis[0] + 9 * axis[1] - 9 * axis[2] + 3 * axis[3];
10476
- if (a !== 0) {
10477
- const b = 6 * axis[0] - 12 * axis[1] + 6 * axis[2];
10478
- const c = -3 * axis[0] + 3 * axis[1];
10479
- const discriminant = b * b - 4 * a * c;
10480
- if (discriminant >= 0) {
10481
- const d = Math.sqrt(discriminant);
10482
- extremaTs.push((-b + d) / (2 * a));
10483
- extremaTs.push((-b - d) / (2 * a));
10484
- }
10485
- }
10486
- }
10487
- return extremaTs
10488
- .filter((t) => t > 0 && t < 1)
10489
- .flatMap((t) => axisPoints.map((axis) => {
10490
- const mt = 1 - t;
10491
- return (mt * mt * mt * axis[0] +
10492
- 3 * mt * mt * t * axis[1] +
10493
- 3 * mt * t * t * axis[2] +
10494
- t * t * t * axis[3]);
10495
- }));
10496
- }
10497
- /**
10498
- * Line constructor.&nbsp; Lines are defined by an array of points and
10499
- * a tension
10500
- * @constructor
10501
- * @memberof Konva
10502
- * @augments Konva.Shape
10503
- * @param {Object} config
10504
- * @param {Array} config.points Flat array of points coordinates. You should define them as [x1, y1, x2, y2, x3, y3].
10505
- * @param {Number} [config.tension] Higher values will result in a more curvy line. A value of 0 will result in no interpolation.
10506
- * The default is 0
10507
- * @param {Boolean} [config.closed] defines whether or not the line shape is closed, creating a polygon or blob
10508
- * @param {Boolean} [config.bezier] if no tension is provided but bezier=true, we draw the line as a bezier using the passed points
10509
- * @param {String} [config.fill] fill color
10510
- * @param {Image} [config.fillPatternImage] fill pattern image
10511
- * @param {Number} [config.fillPatternX]
10512
- * @param {Number} [config.fillPatternY]
10513
- * @param {Object} [config.fillPatternOffset] object with x and y component
10514
- * @param {Number} [config.fillPatternOffsetX]
10515
- * @param {Number} [config.fillPatternOffsetY]
10516
- * @param {Object} [config.fillPatternScale] object with x and y component
10517
- * @param {Number} [config.fillPatternScaleX]
10518
- * @param {Number} [config.fillPatternScaleY]
10519
- * @param {Number} [config.fillPatternRotation]
10520
- * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
10521
- * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
10522
- * @param {Number} [config.fillLinearGradientStartPointX]
10523
- * @param {Number} [config.fillLinearGradientStartPointY]
10524
- * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
10525
- * @param {Number} [config.fillLinearGradientEndPointX]
10526
- * @param {Number} [config.fillLinearGradientEndPointY]
10527
- * @param {Array} [config.fillLinearGradientColorStops] array of color stops
10528
- * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
10529
- * @param {Number} [config.fillRadialGradientStartPointX]
10530
- * @param {Number} [config.fillRadialGradientStartPointY]
10531
- * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
10532
- * @param {Number} [config.fillRadialGradientEndPointX]
10533
- * @param {Number} [config.fillRadialGradientEndPointY]
10534
- * @param {Number} [config.fillRadialGradientStartRadius]
10535
- * @param {Number} [config.fillRadialGradientEndRadius]
10536
- * @param {Array} [config.fillRadialGradientColorStops] array of color stops
10537
- * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
10538
- * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
10539
- * @param {String} [config.stroke] stroke color
10540
- * @param {Number} [config.strokeWidth] stroke width
10541
- * @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
10542
- * @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
10543
- * @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
10544
- * @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
10545
- * @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
10546
- * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
10547
- * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
10548
- * @param {String} [config.lineJoin] can be miter, round, or bevel. The default
10549
- * is miter
10550
- * @param {String} [config.lineCap] can be butt, round, or square. The default
10551
- * is butt
10552
- * @param {String} [config.shadowColor]
10553
- * @param {Number} [config.shadowBlur]
10554
- * @param {Object} [config.shadowOffset] object with x and y component
10555
- * @param {Number} [config.shadowOffsetX]
10556
- * @param {Number} [config.shadowOffsetY]
10557
- * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
10558
- * between 0 and 1
10559
- * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
10560
- * @param {Array} [config.dash]
10561
- * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
10562
-
10563
- * @param {Number} [config.x]
10564
- * @param {Number} [config.y]
10565
- * @param {Number} [config.width]
10566
- * @param {Number} [config.height]
10567
- * @param {Boolean} [config.visible]
10568
- * @param {Boolean} [config.listening] whether or not the node is listening for events
10569
- * @param {String} [config.id] unique id
10570
- * @param {String} [config.name] non-unique name
10571
- * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
10572
- * @param {Object} [config.scale] set scale
10573
- * @param {Number} [config.scaleX] set scale x
10574
- * @param {Number} [config.scaleY] set scale y
10575
- * @param {Number} [config.rotation] rotation in degrees
10576
- * @param {Object} [config.offset] offset from center point and rotation point
10577
- * @param {Number} [config.offsetX] set offset x
10578
- * @param {Number} [config.offsetY] set offset y
10579
- * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
10580
- * the entire stage by dragging any portion of the stage
10581
- * @param {Number} [config.dragDistance]
10582
- * @param {Function} [config.dragBoundFunc]
10583
- * @example
10584
- * var line = new Konva.Line({
10585
- * x: 100,
10586
- * y: 50,
10587
- * points: [73, 70, 340, 23, 450, 60, 500, 20],
10588
- * stroke: 'red',
10589
- * tension: 1
10590
- * });
10591
- */
10592
- class Line extends Shape {
10593
- constructor(config) {
10594
- super(config);
10595
- this.on('pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva', function () {
10596
- this._clearCache('tensionPoints');
10597
- });
10598
- }
10599
- _sceneFunc(context) {
10600
- const points = this.points(), length = points.length, tension = this.tension(), closed = this.closed(), bezier = this.bezier();
10601
- if (!length) {
10602
- return;
10603
- }
10604
- let n = 0;
10605
- context.beginPath();
10606
- context.moveTo(points[0], points[1]);
10607
- // tension
10608
- if (tension !== 0 && length > 4) {
10609
- const tp = this.getTensionPoints();
10610
- const len = tp.length;
10611
- n = closed ? 0 : 4;
10612
- if (!closed) {
10613
- context.quadraticCurveTo(tp[0], tp[1], tp[2], tp[3]);
10614
- }
10615
- while (n < len - 2) {
10616
- context.bezierCurveTo(tp[n++], tp[n++], tp[n++], tp[n++], tp[n++], tp[n++]);
10617
- }
10618
- if (!closed) {
10619
- context.quadraticCurveTo(tp[len - 2], tp[len - 1], points[length - 2], points[length - 1]);
10620
- }
10621
- }
10622
- else if (bezier) {
10623
- // no tension but bezier
10624
- n = 2;
10625
- while (n < length) {
10626
- context.bezierCurveTo(points[n++], points[n++], points[n++], points[n++], points[n++], points[n++]);
10627
- }
10628
- }
10629
- else {
10630
- // no tension
10631
- for (n = 2; n < length; n += 2) {
10632
- context.lineTo(points[n], points[n + 1]);
10633
- }
10634
- }
10635
- // closed e.g. polygons and blobs
10636
- if (closed) {
10637
- context.closePath();
10638
- context.fillStrokeShape(this);
10639
- }
10640
- else {
10641
- // open e.g. lines and splines
10642
- context.strokeShape(this);
10643
- }
10644
- }
10645
- getTensionPoints() {
10646
- return this._getCache('tensionPoints', this._getTensionPoints);
10647
- }
10648
- _getTensionPoints() {
10649
- if (this.closed()) {
10650
- return this._getTensionPointsClosed();
10651
- }
10652
- else {
10653
- return expandPoints(this.points(), this.tension());
10654
- }
10655
- }
10656
- _getTensionPointsClosed() {
10657
- const p = this.points(), len = p.length, tension = this.tension(), firstControlPoints = getControlPoints(p[len - 2], p[len - 1], p[0], p[1], p[2], p[3], tension), lastControlPoints = getControlPoints(p[len - 4], p[len - 3], p[len - 2], p[len - 1], p[0], p[1], tension), middle = expandPoints(p, tension), tp = [firstControlPoints[2], firstControlPoints[3]]
10658
- .concat(middle)
10659
- .concat([
10660
- lastControlPoints[0],
10661
- lastControlPoints[1],
10662
- p[len - 2],
10663
- p[len - 1],
10664
- lastControlPoints[2],
10665
- lastControlPoints[3],
10666
- firstControlPoints[0],
10667
- firstControlPoints[1],
10668
- p[0],
10669
- p[1],
10670
- ]);
10671
- return tp;
10672
- }
10673
- getWidth() {
10674
- return this.getSelfRect().width;
10675
- }
10676
- getHeight() {
10677
- return this.getSelfRect().height;
10678
- }
10679
- // overload size detection
10680
- getSelfRect() {
10681
- let points = this.points();
10682
- if (points.length < 4) {
10683
- return {
10684
- x: points[0] || 0,
10685
- y: points[1] || 0,
10686
- width: 0,
10687
- height: 0,
10688
- };
10689
- }
10690
- if (this.tension() !== 0) {
10691
- points = [
10692
- points[0],
10693
- points[1],
10694
- ...this._getTensionPoints(),
10695
- points[points.length - 2],
10696
- points[points.length - 1],
10697
- ];
10698
- }
10699
- else if (this.bezier()) {
10700
- points = [
10701
- points[0],
10702
- points[1],
10703
- ...getBezierExtremaPoints(this.points()),
10704
- points[points.length - 2],
10705
- points[points.length - 1],
10706
- ];
10707
- }
10708
- else {
10709
- points = this.points();
10710
- }
10711
- let minX = points[0];
10712
- let maxX = points[0];
10713
- let minY = points[1];
10714
- let maxY = points[1];
10715
- let x, y;
10716
- for (let i = 0; i < points.length / 2; i++) {
10717
- x = points[i * 2];
10718
- y = points[i * 2 + 1];
10719
- minX = Math.min(minX, x);
10720
- maxX = Math.max(maxX, x);
10721
- minY = Math.min(minY, y);
10722
- maxY = Math.max(maxY, y);
10723
- }
10724
- return {
10725
- x: minX,
10726
- y: minY,
10727
- width: maxX - minX,
10728
- height: maxY - minY,
10729
- };
10730
- }
10731
- }
10732
- Line.prototype.className = 'Line';
10733
- Line.prototype._attrsAffectingSize = ['points', 'bezier', 'tension'];
10734
- _registerNode(Line);
10735
- // add getters setters
10736
- Factory.addGetterSetter(Line, 'closed', false);
10737
- /**
10738
- * get/set closed flag. The default is false
10739
- * @name Konva.Line#closed
10740
- * @method
10741
- * @param {Boolean} closed
10742
- * @returns {Boolean}
10743
- * @example
10744
- * // get closed flag
10745
- * var closed = line.closed();
10746
- *
10747
- * // close the shape
10748
- * line.closed(true);
10749
- *
10750
- * // open the shape
10751
- * line.closed(false);
10752
- */
10753
- Factory.addGetterSetter(Line, 'bezier', false);
10754
- /**
10755
- * get/set bezier flag. The default is false
10756
- * @name Konva.Line#bezier
10757
- * @method
10758
- * @param {Boolean} bezier
10759
- * @returns {Boolean}
10760
- * @example
10761
- * // get whether the line is a bezier
10762
- * var isBezier = line.bezier();
10763
- *
10764
- * // set whether the line is a bezier
10765
- * line.bezier(true);
10766
- */
10767
- Factory.addGetterSetter(Line, 'tension', 0, getNumberValidator());
10768
- /**
10769
- * get/set tension
10770
- * @name Konva.Line#tension
10771
- * @method
10772
- * @param {Number} tension Higher values will result in a more curvy line. A value of 0 will result in no interpolation. The default is 0
10773
- * @returns {Number}
10774
- * @example
10775
- * // get tension
10776
- * var tension = line.tension();
10777
- *
10778
- * // set tension
10779
- * line.tension(3);
10780
- */
10781
- Factory.addGetterSetter(Line, 'points', [], getNumberArrayValidator());
10782
- /**
10783
- * get/set points array. Points is a flat array [x1, y1, x2, y2]. It is flat for performance reasons.
10784
- * @name Konva.Line#points
10785
- * @method
10786
- * @param {Array} points
10787
- * @returns {Array}
10788
- * @example
10789
- * // get points
10790
- * var points = line.points();
10791
- *
10792
- * // set points
10793
- * line.points([10, 20, 30, 40, 50, 60]);
10794
- *
10795
- * // push a new point
10796
- * line.points(line.points().concat([70, 80]));
10797
- */
10798
-
10799
10749
  // Credits: rveciana/svg-path-properties
10800
10750
  // Legendre-Gauss abscissae (xi values, defined at i=n as the roots of the nth order Legendre polynomial Pn(x))
10801
10751
  const tValues = [
@@ -11534,66 +11484,485 @@ js: import "konva/skia-backend";
11534
11484
  /**
11535
11485
  * Compute the curve derivative (hodograph) at t.
11536
11486
  */
11537
- const getDerivative = (derivative, t, vs) => {
11538
- // the derivative of any 't'-less function is zero.
11539
- const n = vs.length - 1;
11540
- let _vs;
11541
- let value;
11542
- if (n === 0) {
11543
- return 0;
11487
+ const getDerivative = (derivative, t, vs) => {
11488
+ // the derivative of any 't'-less function is zero.
11489
+ const n = vs.length - 1;
11490
+ let _vs;
11491
+ let value;
11492
+ if (n === 0) {
11493
+ return 0;
11494
+ }
11495
+ // direct values? compute!
11496
+ if (derivative === 0) {
11497
+ value = 0;
11498
+ for (let k = 0; k <= n; k++) {
11499
+ value +=
11500
+ binomialCoefficients[n][k] *
11501
+ Math.pow(1 - t, n - k) *
11502
+ Math.pow(t, k) *
11503
+ vs[k];
11504
+ }
11505
+ return value;
11506
+ }
11507
+ else {
11508
+ // Still some derivative? go down one order, then try
11509
+ // for the lower order curve's.
11510
+ _vs = new Array(n);
11511
+ for (let k = 0; k < n; k++) {
11512
+ _vs[k] = n * (vs[k + 1] - vs[k]);
11513
+ }
11514
+ return getDerivative(derivative - 1, t, _vs);
11515
+ }
11516
+ };
11517
+ const t2length = (length, totalLength, func) => {
11518
+ let error = 1;
11519
+ let t = length / totalLength;
11520
+ let step = (length - func(t)) / totalLength;
11521
+ let numIterations = 0;
11522
+ while (error > 0.001) {
11523
+ const increasedTLength = func(t + step);
11524
+ const increasedTError = Math.abs(length - increasedTLength) / totalLength;
11525
+ if (increasedTError < error) {
11526
+ error = increasedTError;
11527
+ t += step;
11528
+ }
11529
+ else {
11530
+ const decreasedTLength = func(t - step);
11531
+ const decreasedTError = Math.abs(length - decreasedTLength) / totalLength;
11532
+ if (decreasedTError < error) {
11533
+ error = decreasedTError;
11534
+ t -= step;
11535
+ }
11536
+ else {
11537
+ step /= 2;
11538
+ }
11539
+ }
11540
+ numIterations++;
11541
+ if (numIterations > 500) {
11542
+ break;
11543
+ }
11544
+ }
11545
+ return t;
11546
+ };
11547
+ const quadraticAt = (p0, p1, p2, t) => {
11548
+ const mt = 1 - t;
11549
+ return mt * mt * p0 + 2 * mt * t * p1 + t * t * p2;
11550
+ };
11551
+ /**
11552
+ * Points where a quadratic bezier segment reaches its highest or lowest value
11553
+ * on one of the two axes, as a flat [x, y, x, y, ...] list. The two end points
11554
+ * are not included, because the caller knows them already.
11555
+ */
11556
+ const getQuadraticExtremaPoints = (x0, y0, x1, y1, x2, y2) => {
11557
+ const extrema = [];
11558
+ for (const axis of [
11559
+ [x0, x1, x2],
11560
+ [y0, y1, y2],
11561
+ ]) {
11562
+ // the derivative of the quadratic is linear, so it has one root. A straight
11563
+ // segment makes the denominator 0, and the division then gives a value that
11564
+ // is not in the range below.
11565
+ const t = (axis[0] - axis[1]) / (axis[0] - 2 * axis[1] + axis[2]);
11566
+ if (t > 0 && t < 1) {
11567
+ extrema.push(quadraticAt(x0, x1, x2, t), quadraticAt(y0, y1, y2, t));
11568
+ }
11569
+ }
11570
+ return extrema;
11571
+ };
11572
+ const cubicAt = (p0, p1, p2, p3, t) => {
11573
+ const mt = 1 - t;
11574
+ return (mt * mt * mt * p0 +
11575
+ 3 * mt * mt * t * p1 +
11576
+ 3 * mt * t * t * p2 +
11577
+ t * t * t * p3);
11578
+ };
11579
+ /**
11580
+ * Points where a cubic bezier segment reaches its highest or lowest value on
11581
+ * one of the two axes, as a flat [x, y, x, y, ...] list. The two end points
11582
+ * are not included, because the caller knows them already.
11583
+ */
11584
+ const getCubicExtremaPoints = (x0, y0, x1, y1, x2, y2, x3, y3) => {
11585
+ const extrema = [];
11586
+ for (const axis of [
11587
+ [x0, x1, x2, x3],
11588
+ [y0, y1, y2, y3],
11589
+ ]) {
11590
+ // the derivative of the cubic is a * t * t + b * t + c
11591
+ const a = -3 * axis[0] + 9 * axis[1] - 9 * axis[2] + 3 * axis[3];
11592
+ const b = 6 * axis[0] - 12 * axis[1] + 6 * axis[2];
11593
+ const c = -3 * axis[0] + 3 * axis[1];
11594
+ const discriminant = b * b - 4 * a * c;
11595
+ if (discriminant < 0) {
11596
+ continue;
11597
+ }
11598
+ // stable form of the quadratic formula. The plain (-b +- d) / (2 * a)
11599
+ // loses the root that stays finite when a is zero or near zero, which is
11600
+ // what a symmetric pair of control points gives. Roots that are not
11601
+ // finite fall out of the range test below.
11602
+ const q = -(b + (b < 0 ? -1 : 1) * Math.sqrt(discriminant)) / 2;
11603
+ for (const t of [q / a, c / q]) {
11604
+ if (t > 0 && t < 1) {
11605
+ extrema.push(cubicAt(x0, x1, x2, x3, t), cubicAt(y0, y1, y2, y3, t));
11606
+ }
11607
+ }
11608
+ }
11609
+ return extrema;
11610
+ };
11611
+
11612
+ function getControlPoints(x0, y0, x1, y1, x2, y2, t) {
11613
+ const d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)), d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), dSum = d01 + d12;
11614
+ // all three points are the same, so the control points collapse into that
11615
+ // point. Without this the divisions below are 0 / 0 = NaN.
11616
+ if (dSum === 0) {
11617
+ return [x1, y1, x1, y1];
11618
+ }
11619
+ const fa = (t * d01) / dSum, fb = (t * d12) / dSum, p1x = x1 - fa * (x2 - x0), p1y = y1 - fa * (y2 - y0), p2x = x1 + fb * (x2 - x0), p2y = y1 + fb * (y2 - y0);
11620
+ return [p1x, p1y, p2x, p2y];
11621
+ }
11622
+ function expandPoints(p, tension) {
11623
+ const len = p.length, allPoints = [];
11624
+ for (let n = 2; n < len - 2; n += 2) {
11625
+ const cp = getControlPoints(p[n - 2], p[n - 1], p[n], p[n + 1], p[n + 2], p[n + 3], tension);
11626
+ if (isNaN(cp[0])) {
11627
+ continue;
11628
+ }
11629
+ allPoints.push(cp[0]);
11630
+ allPoints.push(cp[1]);
11631
+ allPoints.push(p[n]);
11632
+ allPoints.push(p[n + 1]);
11633
+ allPoints.push(cp[2]);
11634
+ allPoints.push(cp[3]);
11635
+ }
11636
+ return allPoints;
11637
+ }
11638
+ function getBezierExtremaPoints(points) {
11639
+ const extrema = [];
11640
+ // points[0], points[1] is the starting point; every subsequent group of
11641
+ // 6 values is one cubic bezier segment (cp1x, cp1y, cp2x, cp2y, x, y),
11642
+ // whose start is the previous segment's end point (matching the layout
11643
+ // Line#_sceneFunc feeds to context.bezierCurveTo in a loop).
11644
+ for (let n = 0; n + 7 < points.length; n += 6) {
11645
+ // the end point of the segment. It is a joint with the next segment, and
11646
+ // the curve can reach its highest or lowest value there without the
11647
+ // derivative going to zero on either side.
11648
+ extrema.push(points[n + 6], points[n + 7], ...getCubicExtremaPoints(points[n], points[n + 1], points[n + 2], points[n + 3], points[n + 4], points[n + 5], points[n + 6], points[n + 7]));
11649
+ }
11650
+ return extrema;
11651
+ }
11652
+ /**
11653
+ * Line constructor.&nbsp; Lines are defined by an array of points and
11654
+ * a tension
11655
+ * @constructor
11656
+ * @memberof Konva
11657
+ * @augments Konva.Shape
11658
+ * @param {Object} config
11659
+ * @param {Array} config.points Flat array of points coordinates. You should define them as [x1, y1, x2, y2, x3, y3].
11660
+ * @param {Number} [config.tension] Higher values will result in a more curvy line. A value of 0 will result in no interpolation.
11661
+ * The default is 0
11662
+ * @param {Boolean} [config.closed] defines whether or not the line shape is closed, creating a polygon or blob
11663
+ * @param {Boolean} [config.bezier] if no tension is provided but bezier=true, we draw the line as a bezier using the passed points
11664
+ * @param {String} [config.fill] fill color
11665
+ * @param {Image} [config.fillPatternImage] fill pattern image
11666
+ * @param {Number} [config.fillPatternX]
11667
+ * @param {Number} [config.fillPatternY]
11668
+ * @param {Object} [config.fillPatternOffset] object with x and y component
11669
+ * @param {Number} [config.fillPatternOffsetX]
11670
+ * @param {Number} [config.fillPatternOffsetY]
11671
+ * @param {Object} [config.fillPatternScale] object with x and y component
11672
+ * @param {Number} [config.fillPatternScaleX]
11673
+ * @param {Number} [config.fillPatternScaleY]
11674
+ * @param {Number} [config.fillPatternRotation]
11675
+ * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat"
11676
+ * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component
11677
+ * @param {Number} [config.fillLinearGradientStartPointX]
11678
+ * @param {Number} [config.fillLinearGradientStartPointY]
11679
+ * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component
11680
+ * @param {Number} [config.fillLinearGradientEndPointX]
11681
+ * @param {Number} [config.fillLinearGradientEndPointY]
11682
+ * @param {Array} [config.fillLinearGradientColorStops] array of color stops
11683
+ * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component
11684
+ * @param {Number} [config.fillRadialGradientStartPointX]
11685
+ * @param {Number} [config.fillRadialGradientStartPointY]
11686
+ * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component
11687
+ * @param {Number} [config.fillRadialGradientEndPointX]
11688
+ * @param {Number} [config.fillRadialGradientEndPointY]
11689
+ * @param {Number} [config.fillRadialGradientStartRadius]
11690
+ * @param {Number} [config.fillRadialGradientEndRadius]
11691
+ * @param {Array} [config.fillRadialGradientColorStops] array of color stops
11692
+ * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true
11693
+ * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration
11694
+ * @param {String} [config.stroke] stroke color
11695
+ * @param {Number} [config.strokeWidth] stroke width
11696
+ * @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false.
11697
+ * @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth
11698
+ * @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true
11699
+ * @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true
11700
+ * @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true
11701
+ * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true
11702
+ * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true
11703
+ * @param {String} [config.lineJoin] can be miter, round, or bevel. The default
11704
+ * is miter
11705
+ * @param {String} [config.lineCap] can be butt, round, or square. The default
11706
+ * is butt
11707
+ * @param {String} [config.shadowColor]
11708
+ * @param {Number} [config.shadowBlur]
11709
+ * @param {Object} [config.shadowOffset] object with x and y component
11710
+ * @param {Number} [config.shadowOffsetX]
11711
+ * @param {Number} [config.shadowOffsetY]
11712
+ * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number
11713
+ * between 0 and 1
11714
+ * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true
11715
+ * @param {Array} [config.dash]
11716
+ * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true
11717
+
11718
+ * @param {Number} [config.x]
11719
+ * @param {Number} [config.y]
11720
+ * @param {Number} [config.width]
11721
+ * @param {Number} [config.height]
11722
+ * @param {Boolean} [config.visible]
11723
+ * @param {Boolean} [config.listening] whether or not the node is listening for events
11724
+ * @param {String} [config.id] unique id
11725
+ * @param {String} [config.name] non-unique name
11726
+ * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1
11727
+ * @param {Object} [config.scale] set scale
11728
+ * @param {Number} [config.scaleX] set scale x
11729
+ * @param {Number} [config.scaleY] set scale y
11730
+ * @param {Number} [config.rotation] rotation in degrees
11731
+ * @param {Object} [config.offset] offset from center point and rotation point
11732
+ * @param {Number} [config.offsetX] set offset x
11733
+ * @param {Number} [config.offsetY] set offset y
11734
+ * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop
11735
+ * the entire stage by dragging any portion of the stage
11736
+ * @param {Number} [config.dragDistance]
11737
+ * @param {Function} [config.dragBoundFunc]
11738
+ * @example
11739
+ * var line = new Konva.Line({
11740
+ * x: 100,
11741
+ * y: 50,
11742
+ * points: [73, 70, 340, 23, 450, 60, 500, 20],
11743
+ * stroke: 'red',
11744
+ * tension: 1
11745
+ * });
11746
+ */
11747
+ class Line extends Shape {
11748
+ constructor(config) {
11749
+ super(config);
11750
+ this.on('pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva', function () {
11751
+ this._clearCache('tensionPoints');
11752
+ });
11544
11753
  }
11545
- // direct values? compute!
11546
- if (derivative === 0) {
11547
- value = 0;
11548
- for (let k = 0; k <= n; k++) {
11549
- value +=
11550
- binomialCoefficients[n][k] *
11551
- Math.pow(1 - t, n - k) *
11552
- Math.pow(t, k) *
11553
- vs[k];
11554
- }
11555
- return value;
11754
+ _hasTension() {
11755
+ return this.tension() !== 0 && this.points().length > 4;
11556
11756
  }
11557
- else {
11558
- // Still some derivative? go down one order, then try
11559
- // for the lower order curve's.
11560
- _vs = new Array(n);
11561
- for (let k = 0; k < n; k++) {
11562
- _vs[k] = n * (vs[k + 1] - vs[k]);
11757
+ /**
11758
+ * Report every curve segment of a line with a tension, in draw order. Both
11759
+ * the scene function and the bounding rect read the shape through this, so
11760
+ * that they can not disagree about which curve the line is.
11761
+ *
11762
+ * The handlers take plain numbers, because this runs on every frame.
11763
+ */
11764
+ _eachTensionSegment(onQuadratic, onCubic) {
11765
+ const points = this.points(), length = points.length, closed = this.closed(), tp = this.getTensionPoints(), len = tp.length;
11766
+ let x0 = points[0], y0 = points[1],
11767
+ // a closed line has a curve on both sides of the first point, so it
11768
+ // starts on a full cubic. An open one is capped by a quadratic instead
11769
+ n = closed ? 0 : 4;
11770
+ if (!closed) {
11771
+ onQuadratic(x0, y0, tp[0], tp[1], tp[2], tp[3]);
11772
+ x0 = tp[2];
11773
+ y0 = tp[3];
11774
+ }
11775
+ while (n < len - 2) {
11776
+ const cp1x = tp[n++], cp1y = tp[n++], cp2x = tp[n++], cp2y = tp[n++], x = tp[n++], y = tp[n++];
11777
+ onCubic(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y);
11778
+ x0 = x;
11779
+ y0 = y;
11780
+ }
11781
+ if (!closed) {
11782
+ onQuadratic(x0, y0, tp[len - 2], tp[len - 1], points[length - 2], points[length - 1]);
11563
11783
  }
11564
- return getDerivative(derivative - 1, t, _vs);
11565
11784
  }
11566
- };
11567
- const t2length = (length, totalLength, func) => {
11568
- let error = 1;
11569
- let t = length / totalLength;
11570
- let step = (length - func(t)) / totalLength;
11571
- let numIterations = 0;
11572
- while (error > 0.001) {
11573
- const increasedTLength = func(t + step);
11574
- const increasedTError = Math.abs(length - increasedTLength) / totalLength;
11575
- if (increasedTError < error) {
11576
- error = increasedTError;
11577
- t += step;
11785
+ _sceneFunc(context) {
11786
+ const points = this.points(), length = points.length, closed = this.closed(), bezier = this.bezier();
11787
+ if (!length) {
11788
+ return;
11578
11789
  }
11579
- else {
11580
- const decreasedTLength = func(t - step);
11581
- const decreasedTError = Math.abs(length - decreasedTLength) / totalLength;
11582
- if (decreasedTError < error) {
11583
- error = decreasedTError;
11584
- t -= step;
11790
+ let n = 0;
11791
+ context.beginPath();
11792
+ context.moveTo(points[0], points[1]);
11793
+ // tension
11794
+ if (this._hasTension()) {
11795
+ this._eachTensionSegment((_x0, _y0, cpx, cpy, x, y) => context.quadraticCurveTo(cpx, cpy, x, y), (_x0, _y0, cp1x, cp1y, cp2x, cp2y, x, y) => context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y));
11796
+ }
11797
+ else if (bezier) {
11798
+ // no tension but bezier
11799
+ n = 2;
11800
+ while (n < length) {
11801
+ context.bezierCurveTo(points[n++], points[n++], points[n++], points[n++], points[n++], points[n++]);
11585
11802
  }
11586
- else {
11587
- step /= 2;
11803
+ }
11804
+ else {
11805
+ // no tension
11806
+ for (n = 2; n < length; n += 2) {
11807
+ context.lineTo(points[n], points[n + 1]);
11588
11808
  }
11589
11809
  }
11590
- numIterations++;
11591
- if (numIterations > 500) {
11592
- break;
11810
+ // closed e.g. polygons and blobs
11811
+ if (closed) {
11812
+ context.closePath();
11813
+ context.fillStrokeShape(this);
11814
+ }
11815
+ else {
11816
+ // open e.g. lines and splines
11817
+ context.strokeShape(this);
11593
11818
  }
11594
11819
  }
11595
- return t;
11596
- };
11820
+ getTensionPoints() {
11821
+ return this._getCache('tensionPoints', this._getTensionPoints);
11822
+ }
11823
+ _getTensionPoints() {
11824
+ if (this.closed()) {
11825
+ return this._getTensionPointsClosed();
11826
+ }
11827
+ else {
11828
+ return expandPoints(this.points(), this.tension());
11829
+ }
11830
+ }
11831
+ _getTensionPointsClosed() {
11832
+ const p = this.points(), len = p.length, tension = this.tension(), firstControlPoints = getControlPoints(p[len - 2], p[len - 1], p[0], p[1], p[2], p[3], tension), lastControlPoints = getControlPoints(p[len - 4], p[len - 3], p[len - 2], p[len - 1], p[0], p[1], tension), middle = expandPoints(p, tension), tp = [firstControlPoints[2], firstControlPoints[3]]
11833
+ .concat(middle)
11834
+ .concat([
11835
+ lastControlPoints[0],
11836
+ lastControlPoints[1],
11837
+ p[len - 2],
11838
+ p[len - 1],
11839
+ lastControlPoints[2],
11840
+ lastControlPoints[3],
11841
+ firstControlPoints[0],
11842
+ firstControlPoints[1],
11843
+ p[0],
11844
+ p[1],
11845
+ ]);
11846
+ return tp;
11847
+ }
11848
+ getWidth() {
11849
+ return this.getSelfRect().width;
11850
+ }
11851
+ getHeight() {
11852
+ return this.getSelfRect().height;
11853
+ }
11854
+ // overload size detection
11855
+ getSelfRect() {
11856
+ let points = this.points();
11857
+ if (points.length < 4) {
11858
+ return {
11859
+ x: points[0] || 0,
11860
+ y: points[1] || 0,
11861
+ width: 0,
11862
+ height: 0,
11863
+ };
11864
+ }
11865
+ if (this._hasTension()) {
11866
+ // the two end points of every segment, plus the points where it turns
11867
+ // back on either axis. Together they are the exact bounds of the curve
11868
+ const bounds = [points[0], points[1]];
11869
+ this._eachTensionSegment((x0, y0, cpx, cpy, x, y) => bounds.push(x, y, ...getQuadraticExtremaPoints(x0, y0, cpx, cpy, x, y)), (x0, y0, cp1x, cp1y, cp2x, cp2y, x, y) => bounds.push(x, y, ...getCubicExtremaPoints(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y)));
11870
+ points = bounds;
11871
+ }
11872
+ else if (this.bezier()) {
11873
+ // no trailing point here: the extrema already carry the end point of
11874
+ // every segment that is drawn. Adding the last pair of the array back
11875
+ // would include a control point of a trailing partial segment, which
11876
+ // _sceneFunc never draws.
11877
+ points = [points[0], points[1], ...getBezierExtremaPoints(points)];
11878
+ }
11879
+ let minX = points[0];
11880
+ let maxX = points[0];
11881
+ let minY = points[1];
11882
+ let maxY = points[1];
11883
+ let x, y;
11884
+ for (let i = 0; i < points.length / 2; i++) {
11885
+ x = points[i * 2];
11886
+ y = points[i * 2 + 1];
11887
+ minX = Math.min(minX, x);
11888
+ maxX = Math.max(maxX, x);
11889
+ minY = Math.min(minY, y);
11890
+ maxY = Math.max(maxY, y);
11891
+ }
11892
+ return {
11893
+ x: minX,
11894
+ y: minY,
11895
+ width: maxX - minX,
11896
+ height: maxY - minY,
11897
+ };
11898
+ }
11899
+ }
11900
+ Line.prototype.className = 'Line';
11901
+ Line.prototype._attrsAffectingSize = ['points', 'bezier', 'tension'];
11902
+ _registerNode(Line);
11903
+ // add getters setters
11904
+ Factory.addGetterSetter(Line, 'closed', false);
11905
+ /**
11906
+ * get/set closed flag. The default is false
11907
+ * @name Konva.Line#closed
11908
+ * @method
11909
+ * @param {Boolean} closed
11910
+ * @returns {Boolean}
11911
+ * @example
11912
+ * // get closed flag
11913
+ * var closed = line.closed();
11914
+ *
11915
+ * // close the shape
11916
+ * line.closed(true);
11917
+ *
11918
+ * // open the shape
11919
+ * line.closed(false);
11920
+ */
11921
+ Factory.addGetterSetter(Line, 'bezier', false);
11922
+ /**
11923
+ * get/set bezier flag. The default is false
11924
+ * @name Konva.Line#bezier
11925
+ * @method
11926
+ * @param {Boolean} bezier
11927
+ * @returns {Boolean}
11928
+ * @example
11929
+ * // get whether the line is a bezier
11930
+ * var isBezier = line.bezier();
11931
+ *
11932
+ * // set whether the line is a bezier
11933
+ * line.bezier(true);
11934
+ */
11935
+ Factory.addGetterSetter(Line, 'tension', 0, getNumberValidator());
11936
+ /**
11937
+ * get/set tension
11938
+ * @name Konva.Line#tension
11939
+ * @method
11940
+ * @param {Number} tension Higher values will result in a more curvy line. A value of 0 will result in no interpolation. The default is 0
11941
+ * @returns {Number}
11942
+ * @example
11943
+ * // get tension
11944
+ * var tension = line.tension();
11945
+ *
11946
+ * // set tension
11947
+ * line.tension(3);
11948
+ */
11949
+ Factory.addGetterSetter(Line, 'points', [], getNumberArrayValidator());
11950
+ /**
11951
+ * get/set points array. Points is a flat array [x1, y1, x2, y2]. It is flat for performance reasons.
11952
+ * @name Konva.Line#points
11953
+ * @method
11954
+ * @param {Array} points
11955
+ * @returns {Array}
11956
+ * @example
11957
+ * // get points
11958
+ * var points = line.points();
11959
+ *
11960
+ * // set points
11961
+ * line.points([10, 20, 30, 40, 50, 60]);
11962
+ *
11963
+ * // push a new point
11964
+ * line.points(line.points().concat([70, 80]));
11965
+ */
11597
11966
 
11598
11967
  /**
11599
11968
  * Path constructor.
@@ -11779,14 +12148,16 @@ js: import "konva/skia-backend";
11779
12148
  }
11780
12149
  }
11781
12150
  else if (data.command === 'C') {
11782
- // Approximates by breaking curve into 100 line segments
11783
- for (let t = 0.0; t <= 1; t += 0.01) {
11784
- const point = Path.getPointOnCubicBezier(t, data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5]);
11785
- points.push(point.x, point.y);
11786
- }
12151
+ // the two end points, plus the points where the curve turns back on
12152
+ // either axis. Together they are the exact bounds of the segment
12153
+ points.push(data.start.x, data.start.y, data.points[4], data.points[5], ...getCubicExtremaPoints(data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5]));
12154
+ }
12155
+ else if (data.command === 'Q') {
12156
+ // same as 'C'. Note that 'q', 'T' and 't' are all normalised to 'Q' by
12157
+ // the parser, so this one branch covers every quadratic segment
12158
+ points.push(data.start.x, data.start.y, data.points[2], data.points[3], ...getQuadraticExtremaPoints(data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3]));
11787
12159
  }
11788
12160
  else {
11789
- // TODO: how can we calculate bezier curves better?
11790
12161
  points = points.concat(data.points);
11791
12162
  }
11792
12163
  });
@@ -11858,7 +12229,11 @@ js: import "konva/skia-backend";
11858
12229
  ++i;
11859
12230
  }
11860
12231
  if (i === ii) {
11861
- points = dataArray[i - 1].points.slice(-2);
12232
+ let j = i - 1;
12233
+ while (j > 0 && dataArray[j].points.length < 2) {
12234
+ j--;
12235
+ }
12236
+ points = dataArray[j].points.slice(-2);
11862
12237
  return {
11863
12238
  x: points[0],
11864
12239
  y: points[1],
@@ -14778,10 +15153,17 @@ js: import "konva/skia-backend";
14778
15153
  return dummyContext;
14779
15154
  }
14780
15155
  function _fillFunc$1(context) {
15156
+ // re-apply a per-character style set by charRenderFunc (see _sceneFunc)
15157
+ if (this._partialFillStyle) {
15158
+ context.setAttr('fillStyle', this._partialFillStyle);
15159
+ }
14781
15160
  context.fillText(this._partialText, this._partialTextX, this._partialTextY);
14782
15161
  }
14783
15162
  function _strokeFunc$1(context) {
14784
15163
  context.setAttr('miterLimit', 2);
15164
+ if (this._partialStrokeStyle) {
15165
+ context.setAttr('strokeStyle', this._partialStrokeStyle);
15166
+ }
14785
15167
  context.strokeText(this._partialText, this._partialTextX, this._partialTextY);
14786
15168
  }
14787
15169
  function checkDefaultFill(config) {
@@ -14940,6 +15322,11 @@ js: import "konva/skia-backend";
14940
15322
  alignY = this.getHeight() - textArrLen * lineHeightPx - padding * 2;
14941
15323
  }
14942
15324
  context.translate(padding, alignY + padding);
15325
+ // context styles entering the loop, used to detect styles set by
15326
+ // charRenderFunc; every character is drawn inside save()/restore(),
15327
+ // so the entry state is the same for each one
15328
+ const fillStyleBefore = charRenderFunc ? context.fillStyle : undefined;
15329
+ const strokeStyleBefore = charRenderFunc ? context.strokeStyle : undefined;
14943
15330
  // draw text lines
14944
15331
  for (n = 0; n < textArrLen; n++) {
14945
15332
  let lineTranslateX = 0;
@@ -15011,9 +15398,22 @@ js: import "konva/skia-backend";
15011
15398
  width: this.measureSize(letter).width,
15012
15399
  context,
15013
15400
  });
15401
+ // a style the callback set on the context wins for this character;
15402
+ // fillStrokeShape() overwrites the context styles from the shape
15403
+ // attributes, so stash them for _fillFunc/_strokeFunc to re-apply
15404
+ const fillStyleAfter = context.fillStyle;
15405
+ if (fillStyleAfter !== fillStyleBefore) {
15406
+ this._partialFillStyle = fillStyleAfter;
15407
+ }
15408
+ const strokeStyleAfter = context.strokeStyle;
15409
+ if (strokeStyleAfter !== strokeStyleBefore) {
15410
+ this._partialStrokeStyle = strokeStyleAfter;
15411
+ }
15014
15412
  }
15015
15413
  context.fillStrokeShape(this);
15016
15414
  if (charRenderFunc) {
15415
+ this._partialFillStyle = undefined;
15416
+ this._partialStrokeStyle = undefined;
15017
15417
  context.restore();
15018
15418
  }
15019
15419
  lineTranslateX += this.measureSize(letter).width + letterSpacing;
@@ -15171,16 +15571,21 @@ js: import "konva/skia-backend";
15171
15571
  * break the line into multiple fitting lines
15172
15572
  */
15173
15573
  while (line.length > 0) {
15574
+ // Compute the grapheme array once per iteration. `line` is constant
15575
+ // within this block (only reassigned at the bottom), so calling
15576
+ // `stringToArray(line)` inside the binary search and again afterwards
15577
+ // is redundant and makes resize O(N·logN) on long text.
15578
+ const lineArray = stringToArray(line);
15174
15579
  /*
15175
15580
  * use binary search to find the longest substring that
15176
15581
  * that would fit in the specified width
15177
15582
  */
15178
- let low = 0, high = stringToArray(line).length, // Convert to array for proper emoji handling
15583
+ let low = 0, high = lineArray.length, // Convert to array for proper emoji handling
15179
15584
  match = '', matchWidth = 0;
15180
15585
  while (low < high) {
15181
15586
  const mid = (low + high) >>> 1,
15182
15587
  // Convert array indices to string
15183
- lineArray = stringToArray(line), substr = lineArray.slice(0, mid + 1).join(''), substrWidth = this._getTextWidth(substr);
15588
+ substr = lineArray.slice(0, mid + 1).join(''), substrWidth = this._getTextWidth(substr);
15184
15589
  // Only add ellipsis width when we need to consider truncation
15185
15590
  // for the current line (when it might be the last visible line)
15186
15591
  const shouldConsiderEllipsis = shouldAddEllipsis &&
@@ -15207,7 +15612,6 @@ js: import "konva/skia-backend";
15207
15612
  // a fitting substring was found
15208
15613
  if (wrapAtWord) {
15209
15614
  // try to find a space or dash where wrapping could be done
15210
- const lineArray = stringToArray(line);
15211
15615
  const matchArray = stringToArray(match);
15212
15616
  const nextChar = lineArray[matchArray.length];
15213
15617
  const nextIsSpaceOrDash = nextChar === SPACE || nextChar === DASH;
@@ -15242,8 +15646,7 @@ js: import "konva/skia-backend";
15242
15646
  */
15243
15647
  break;
15244
15648
  }
15245
- // Convert remaining text using array operations
15246
- const lineArray = stringToArray(line);
15649
+ // Reuse the cached `lineArray` to compute the remaining text.
15247
15650
  line = lineArray.slice(low).join('').trimLeft();
15248
15651
  if (line.length > 0) {
15249
15652
  lineWidth = this._getTextWidth(line);
@@ -15605,10 +16008,11 @@ js: import "konva/skia-backend";
15605
16008
  * @param {Function} charRenderFunc
15606
16009
  * @returns {Function}
15607
16010
  * @example
15608
- * // apply small x-translation to every second character
16011
+ * // apply small x-translation and a custom color to every second character
15609
16012
  * text.charRenderFunc(function(props) {
15610
16013
  * if (props.index % 2 === 1) {
15611
16014
  * props.context.translate(2, 0);
16015
+ * props.context.fillStyle = 'red';
15612
16016
  * }
15613
16017
  * });
15614
16018
  */
@@ -16406,7 +16810,11 @@ js: import "konva/skia-backend";
16406
16810
  super(config);
16407
16811
  this._movingAnchorName = null;
16408
16812
  this._transforming = false;
16813
+ // the window the transform events are listened to. The stage may be
16814
+ // rendered in another window than the one Konva was imported into
16815
+ this._transformWindow = null;
16409
16816
  this._elementsCreated = false;
16817
+ this._updateScheduled = false;
16410
16818
  this._createElements();
16411
16819
  // bindings
16412
16820
  this._handleMouseMove = this._handleMouseMove.bind(this);
@@ -16461,12 +16869,22 @@ js: import "konva/skia-backend";
16461
16869
  }
16462
16870
  this._nodes.forEach((node) => {
16463
16871
  const onChange = () => {
16872
+ // Perf: skip during anchor drag — _fitNodesInto does the final
16873
+ // _resetTransformCache + update itself, so per-attr fan-out here is
16874
+ // pure waste (was O(N*events) per resize step).
16875
+ if (this._transforming)
16876
+ return;
16464
16877
  if (this.nodes().length === 1 && this.useSingleNodeRotation()) {
16465
16878
  this.rotation(this.nodes()[0].getAbsoluteRotation());
16466
16879
  }
16880
+ // Cache reset stays synchronous so sync reads of tr.x() etc. are fresh.
16467
16881
  this._resetTransformCache();
16468
- if (!this._transforming && !this.isDragging()) {
16469
- this.update();
16882
+ if (!this.isDragging()) {
16883
+ // Perf: an ancestor cascade (e.g. stage drag) fires
16884
+ // absoluteTransformChange on every attached node — without batching,
16885
+ // update() runs once per node and each call walks all N nodes via
16886
+ // __getNodeRect, giving O(N^2) per drag frame.
16887
+ this._scheduleUpdate();
16470
16888
  }
16471
16889
  };
16472
16890
  if (node._attrsAffectingSize.length) {
@@ -16801,6 +17219,7 @@ js: import "konva/skia-backend";
16801
17219
  });
16802
17220
  }
16803
17221
  _handleMouseDown(e) {
17222
+ var _a;
16804
17223
  // do nothing if we already transforming
16805
17224
  // that is possible to trigger with multitouch
16806
17225
  if (this._transforming) {
@@ -16813,11 +17232,14 @@ js: import "konva/skia-backend";
16813
17232
  const hypotenuse = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
16814
17233
  this.sin = Math.abs(height / hypotenuse);
16815
17234
  this.cos = Math.abs(width / hypotenuse);
16816
- if (typeof window !== 'undefined') {
16817
- window.addEventListener('mousemove', this._handleMouseMove);
16818
- window.addEventListener('touchmove', this._handleMouseMove);
16819
- window.addEventListener('mouseup', this._handleMouseUp, true);
16820
- window.addEventListener('touchend', this._handleMouseUp, true);
17235
+ // the window that owns the stage is the one that gets the pointer events
17236
+ const win = (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._getOwnerWindow();
17237
+ this._transformWindow = win || null;
17238
+ if (win) {
17239
+ win.addEventListener('mousemove', this._handleMouseMove);
17240
+ win.addEventListener('touchmove', this._handleMouseMove);
17241
+ win.addEventListener('mouseup', this._handleMouseUp, true);
17242
+ win.addEventListener('touchend', this._handleMouseUp, true);
16821
17243
  }
16822
17244
  this._transforming = true;
16823
17245
  const ap = e.target.getAbsolutePosition();
@@ -16885,8 +17307,13 @@ js: import "konva/skia-backend";
16885
17307
  keepProportion = this.keepRatio() || e.shiftKey;
16886
17308
  }
16887
17309
  let centeredScaling = this.centeredScaling() || e.altKey;
17310
+ // with keepRatio, a corner anchor doesn't follow the pointer — the blocks
17311
+ // below project it onto the ratio diagonal. _doFitNodesInto must know
17312
+ // that to skip the padding flip compensation (issue #1878)
17313
+ let anchorProjected = false;
16888
17314
  if (this._movingAnchorName === 'top-left') {
16889
17315
  if (keepProportion) {
17316
+ anchorProjected = true;
16890
17317
  const comparePoint = centeredScaling
16891
17318
  ? {
16892
17319
  x: this.width() / 2,
@@ -16911,6 +17338,7 @@ js: import "konva/skia-backend";
16911
17338
  }
16912
17339
  else if (this._movingAnchorName === 'top-right') {
16913
17340
  if (keepProportion) {
17341
+ anchorProjected = true;
16914
17342
  const comparePoint = centeredScaling
16915
17343
  ? {
16916
17344
  x: this.width() / 2,
@@ -16941,6 +17369,7 @@ js: import "konva/skia-backend";
16941
17369
  }
16942
17370
  else if (this._movingAnchorName === 'bottom-left') {
16943
17371
  if (keepProportion) {
17372
+ anchorProjected = true;
16944
17373
  const comparePoint = centeredScaling
16945
17374
  ? {
16946
17375
  x: this.width() / 2,
@@ -16968,6 +17397,7 @@ js: import "konva/skia-backend";
16968
17397
  }
16969
17398
  else if (this._movingAnchorName === 'bottom-right') {
16970
17399
  if (keepProportion) {
17400
+ anchorProjected = true;
16971
17401
  const comparePoint = centeredScaling
16972
17402
  ? {
16973
17403
  x: this.width() / 2,
@@ -17019,7 +17449,7 @@ js: import "konva/skia-backend";
17019
17449
  width: width,
17020
17450
  height: height,
17021
17451
  rotation: Konva$2.getAngle(this.rotation()),
17022
- }, e);
17452
+ }, e, anchorProjected);
17023
17453
  }
17024
17454
  _handleMouseUp(e) {
17025
17455
  this._removeEvents(e);
@@ -17031,11 +17461,13 @@ js: import "konva/skia-backend";
17031
17461
  var _a;
17032
17462
  if (this._transforming) {
17033
17463
  this._transforming = false;
17034
- if (typeof window !== 'undefined') {
17035
- window.removeEventListener('mousemove', this._handleMouseMove);
17036
- window.removeEventListener('touchmove', this._handleMouseMove);
17037
- window.removeEventListener('mouseup', this._handleMouseUp, true);
17038
- window.removeEventListener('touchend', this._handleMouseUp, true);
17464
+ const win = this._transformWindow;
17465
+ this._transformWindow = null;
17466
+ if (win) {
17467
+ win.removeEventListener('mousemove', this._handleMouseMove);
17468
+ win.removeEventListener('touchmove', this._handleMouseMove);
17469
+ win.removeEventListener('mouseup', this._handleMouseUp, true);
17470
+ win.removeEventListener('touchend', this._handleMouseUp, true);
17039
17471
  }
17040
17472
  const node = this.getNode();
17041
17473
  activeTransformersCount--;
@@ -17053,7 +17485,20 @@ js: import "konva/skia-backend";
17053
17485
  this._movingAnchorName = null;
17054
17486
  }
17055
17487
  }
17056
- _fitNodesInto(newAttrs, evt) {
17488
+ _fitNodesInto(newAttrs, evt, anchorProjected = false) {
17489
+ // Perf: suspend autoDraw for the whole method so per-attr _setAttr writes
17490
+ // don't each trigger _requestDraw -> getLayer parent-chain walks.
17491
+ // batchDraw per affected layer is issued at the end.
17492
+ const prevAutoDraw = Konva$2.autoDrawEnabled;
17493
+ Konva$2.autoDrawEnabled = false;
17494
+ try {
17495
+ return this._doFitNodesInto(newAttrs, evt, anchorProjected);
17496
+ }
17497
+ finally {
17498
+ Konva$2.autoDrawEnabled = prevAutoDraw;
17499
+ }
17500
+ }
17501
+ _doFitNodesInto(newAttrs, evt, anchorProjected = false) {
17057
17502
  const oldAttrs = this._getNodeRect();
17058
17503
  const minSize = 1;
17059
17504
  if (Util._inRange(newAttrs.width, -this.padding() * 2 - minSize, minSize)) {
@@ -17066,57 +17511,58 @@ js: import "konva/skia-backend";
17066
17511
  }
17067
17512
  const t = new Transform();
17068
17513
  t.rotate(Konva$2.getAngle(this.rotation()));
17514
+ // the ±2*padding shifts below assume the box size passed through zero
17515
+ // continuously (the anchor tied to the pointer). A projected anchor snaps
17516
+ // the box across zero instead; the shifts then leave the drag state
17517
+ // inconsistent with the real anchor position and the box flips back and
17518
+ // forth on every following move (issue #1878) — so flip only the anchor
17519
+ // name, exactly as when padding is 0.
17520
+ const flipPadding = anchorProjected ? 0 : this.padding() * 2;
17521
+ let widthFlip = null;
17522
+ let heightFlip = null;
17069
17523
  if (this._movingAnchorName &&
17070
17524
  newAttrs.width < 0 &&
17071
17525
  this._movingAnchorName.indexOf('left') >= 0) {
17072
17526
  const offset = t.point({
17073
- x: -this.padding() * 2,
17527
+ x: -flipPadding,
17074
17528
  y: 0,
17075
17529
  });
17076
17530
  newAttrs.x += offset.x;
17077
17531
  newAttrs.y += offset.y;
17078
- newAttrs.width += this.padding() * 2;
17079
- this._movingAnchorName = this._movingAnchorName.replace('left', 'right');
17080
- this._anchorDragOffset.x -= offset.x;
17081
- this._anchorDragOffset.y -= offset.y;
17532
+ newAttrs.width += flipPadding;
17533
+ widthFlip = { axis: 'width', from: 'left', to: 'right', offset };
17082
17534
  }
17083
17535
  else if (this._movingAnchorName &&
17084
17536
  newAttrs.width < 0 &&
17085
17537
  this._movingAnchorName.indexOf('right') >= 0) {
17086
17538
  const offset = t.point({
17087
- x: this.padding() * 2,
17539
+ x: flipPadding,
17088
17540
  y: 0,
17089
17541
  });
17090
- this._movingAnchorName = this._movingAnchorName.replace('right', 'left');
17091
- this._anchorDragOffset.x -= offset.x;
17092
- this._anchorDragOffset.y -= offset.y;
17093
- newAttrs.width += this.padding() * 2;
17542
+ newAttrs.width += flipPadding;
17543
+ widthFlip = { axis: 'width', from: 'right', to: 'left', offset };
17094
17544
  }
17095
17545
  if (this._movingAnchorName &&
17096
17546
  newAttrs.height < 0 &&
17097
17547
  this._movingAnchorName.indexOf('top') >= 0) {
17098
17548
  const offset = t.point({
17099
17549
  x: 0,
17100
- y: -this.padding() * 2,
17550
+ y: -flipPadding,
17101
17551
  });
17102
17552
  newAttrs.x += offset.x;
17103
17553
  newAttrs.y += offset.y;
17104
- this._movingAnchorName = this._movingAnchorName.replace('top', 'bottom');
17105
- this._anchorDragOffset.x -= offset.x;
17106
- this._anchorDragOffset.y -= offset.y;
17107
- newAttrs.height += this.padding() * 2;
17554
+ newAttrs.height += flipPadding;
17555
+ heightFlip = { axis: 'height', from: 'top', to: 'bottom', offset };
17108
17556
  }
17109
17557
  else if (this._movingAnchorName &&
17110
17558
  newAttrs.height < 0 &&
17111
17559
  this._movingAnchorName.indexOf('bottom') >= 0) {
17112
17560
  const offset = t.point({
17113
17561
  x: 0,
17114
- y: this.padding() * 2,
17562
+ y: flipPadding,
17115
17563
  });
17116
- this._movingAnchorName = this._movingAnchorName.replace('bottom', 'top');
17117
- this._anchorDragOffset.x -= offset.x;
17118
- this._anchorDragOffset.y -= offset.y;
17119
- newAttrs.height += this.padding() * 2;
17564
+ newAttrs.height += flipPadding;
17565
+ heightFlip = { axis: 'height', from: 'bottom', to: 'top', offset };
17120
17566
  }
17121
17567
  if (this.boundBoxFunc()) {
17122
17568
  const bounded = this.boundBoxFunc()(oldAttrs, newAttrs);
@@ -17127,6 +17573,15 @@ js: import "konva/skia-backend";
17127
17573
  Util.warn('boundBoxFunc returned falsy. You should return new bound rect from it!');
17128
17574
  }
17129
17575
  }
17576
+ // a staged flip survived only if the bounded size is still negative on
17577
+ // its axis
17578
+ for (const flip of [widthFlip, heightFlip]) {
17579
+ if (flip && newAttrs[flip.axis] < 0 && this._movingAnchorName) {
17580
+ this._movingAnchorName = this._movingAnchorName.replace(flip.from, flip.to);
17581
+ this._anchorDragOffset.x -= flip.offset.x;
17582
+ this._anchorDragOffset.y -= flip.offset.y;
17583
+ }
17584
+ }
17130
17585
  // base size value doesn't really matter
17131
17586
  // we just need to think about bounding boxes as transforms
17132
17587
  // but how?
@@ -17157,8 +17612,10 @@ js: import "konva/skia-backend";
17157
17612
  // that means that
17158
17613
  // [delta transform] = [new transform] * [old transform inverted]
17159
17614
  const delta = newTr.multiply(oldTr.invert());
17615
+ // Perf: collect unique affected layers and batchDraw each once at the end
17616
+ // (was once per node — O(N)).
17617
+ const layersToDraw = new Set();
17160
17618
  this._nodes.forEach((node) => {
17161
- var _a;
17162
17619
  // check to close this issue: https://github.com/konvajs/konva/issues/1957
17163
17620
  // a node can be destroyed during the transformation
17164
17621
  // probably a developer must remove it from transformer
@@ -17186,7 +17643,10 @@ js: import "konva/skia-backend";
17186
17643
  .multiply(localTransform);
17187
17644
  const attrs = newLocalTransform.decompose();
17188
17645
  node.setAttrs(attrs);
17189
- (_a = node.getLayer()) === null || _a === void 0 ? void 0 : _a.batchDraw();
17646
+ const layer = node.getLayer();
17647
+ if (layer) {
17648
+ layersToDraw.add(layer);
17649
+ }
17190
17650
  });
17191
17651
  this.rotation(Util._getRotation(newAttrs.rotation));
17192
17652
  // trigger transform event AFTER we update rotation
@@ -17196,7 +17656,24 @@ js: import "konva/skia-backend";
17196
17656
  });
17197
17657
  this._resetTransformCache();
17198
17658
  this.update();
17199
- this.getLayer().batchDraw();
17659
+ layersToDraw.add(this.getLayer());
17660
+ layersToDraw.forEach((layer) => layer && layer.batchDraw());
17661
+ }
17662
+ // Inside an absoluteTransform cascade, queue a single update to run when
17663
+ // the cascade ends; outside a cascade, run synchronously so reads of
17664
+ // transformer state stay consistent.
17665
+ _scheduleUpdate() {
17666
+ if (this._updateScheduled)
17667
+ return;
17668
+ this._updateScheduled = true;
17669
+ Node._runAfterAbsTransformCascade(() => {
17670
+ var _a;
17671
+ this._updateScheduled = false;
17672
+ if (!((_a = this._nodes) === null || _a === void 0 ? void 0 : _a.length) || this._transforming || this.isDragging()) {
17673
+ return;
17674
+ }
17675
+ this.update();
17676
+ });
17200
17677
  }
17201
17678
  /**
17202
17679
  * force update of Konva.Transformer.
@@ -19028,7 +19505,7 @@ js: import "konva/skia-backend";
19028
19505
  //Konva.Filters.ToPolar = Util._FilterWrapDoubleBuffer(ToPolar);
19029
19506
  //Konva.Filters.FromPolar = Util._FilterWrapDoubleBuffer(FromPolar);
19030
19507
  // create a temporary canvas for working - shared between multiple calls
19031
- /*
19508
+ /**
19032
19509
  * Kaleidoscope Filter.
19033
19510
  * @function
19034
19511
  * @name Kaleidoscope