konva 10.6.0 → 10.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +12 -8
  2. package/konva.js +617 -231
  3. package/konva.min.js +4 -4
  4. package/lib/Canvas.d.ts +9 -2
  5. package/lib/Canvas.js +83 -5
  6. package/lib/Container.d.ts +3 -2
  7. package/lib/Container.js +27 -12
  8. package/lib/Context.d.ts +5 -2
  9. package/lib/Context.js +22 -1
  10. package/lib/Global.d.ts +2 -1
  11. package/lib/Global.js +8 -3
  12. package/lib/Group.d.ts +7 -1
  13. package/lib/Group.js +61 -0
  14. package/lib/Layer.d.ts +1 -1
  15. package/lib/Layer.js +4 -2
  16. package/lib/Node.d.ts +12 -7
  17. package/lib/Node.js +53 -44
  18. package/lib/Shape.d.ts +9 -15
  19. package/lib/Shape.js +145 -85
  20. package/lib/Stage.d.ts +0 -2
  21. package/lib/Stage.js +2 -13
  22. package/lib/Util.d.ts +1 -0
  23. package/lib/Util.js +25 -0
  24. package/lib/shapes/Arc.js +3 -3
  25. package/lib/shapes/Arrow.d.ts +1 -0
  26. package/lib/shapes/Arrow.js +7 -1
  27. package/lib/shapes/Circle.d.ts +1 -0
  28. package/lib/shapes/Circle.js +4 -1
  29. package/lib/shapes/Ellipse.d.ts +1 -0
  30. package/lib/shapes/Ellipse.js +4 -1
  31. package/lib/shapes/Image.d.ts +2 -1
  32. package/lib/shapes/Image.js +6 -3
  33. package/lib/shapes/Label.js +18 -20
  34. package/lib/shapes/Line.d.ts +1 -0
  35. package/lib/shapes/Line.js +4 -1
  36. package/lib/shapes/Path.js +1 -1
  37. package/lib/shapes/Rect.d.ts +1 -0
  38. package/lib/shapes/Rect.js +4 -1
  39. package/lib/shapes/RegularPolygon.js +1 -1
  40. package/lib/shapes/Ring.d.ts +7 -0
  41. package/lib/shapes/Ring.js +8 -1
  42. package/lib/shapes/Sprite.d.ts +2 -1
  43. package/lib/shapes/Sprite.js +6 -3
  44. package/lib/shapes/Star.d.ts +6 -0
  45. package/lib/shapes/Star.js +5 -1
  46. package/lib/shapes/Text.d.ts +5 -2
  47. package/lib/shapes/Text.js +49 -22
  48. package/lib/shapes/TextPath.d.ts +7 -0
  49. package/lib/shapes/TextPath.js +16 -1
  50. package/lib/shapes/Transformer.d.ts +10 -2
  51. package/lib/shapes/Transformer.js +55 -6
  52. package/lib/shapes/Wedge.js +1 -1
  53. package/package.json +2 -18
package/lib/Node.js CHANGED
@@ -4,7 +4,7 @@ import { DD } from "./DragAndDrop.js";
4
4
  import * as PointerEvents from "./PointerEvents.js";
5
5
  import { Factory } from "./Factory.js";
6
6
  import { Konva } from "./Global.js";
7
- import { Transform, Util } from "./Util.js";
7
+ import { Transform, TypedArray, Util } from "./Util.js";
8
8
  import { getBooleanValidator, getNumberValidator, getStringValidator, } from "./Validators.js";
9
9
  // CSS filter parser for fallback to function filters.
10
10
  function parseCSSFilters(cssFilter) {
@@ -97,20 +97,6 @@ const ABSOLUTE_OPACITY = 'absoluteOpacity', ABSOLUTE_TRANSFORM = 'absoluteTransf
97
97
  'transformsEnabledChange.konva',
98
98
  ].join(SPACE);
99
99
  let idCounter = 1;
100
- // "perfect drawing" buffer for cache() and toCanvas(): it mirrors the target
101
- // canvas and is drawn back at (x, y) in the target's coordinate space.
102
- // It starts empty and Shape.drawScene sizes it on first use, so nodes
103
- // without buffered shapes never allocate it.
104
- function createBufferCanvas(target, x, y) {
105
- const bufferCanvas = new SceneCanvas({
106
- width: 0,
107
- height: 0,
108
- pixelRatio: target.pixelRatio,
109
- });
110
- bufferCanvas.x = x;
111
- bufferCanvas.y = y;
112
- return bufferCanvas;
113
- }
114
100
  /**
115
101
  * Node constructor. Nodes are entities that can be transformed, layered,
116
102
  * and have bound events. The stage, layers, groups, and shapes all extend Node.
@@ -304,7 +290,6 @@ export class Node {
304
290
  height: 0,
305
291
  willReadFrequently: true,
306
292
  }), sceneContext = cachedSceneCanvas.getContext();
307
- const bufferCanvas = createBufferCanvas(cachedSceneCanvas, x, y);
308
293
  cachedSceneCanvas.isCache = true;
309
294
  this._releaseCanvasCache();
310
295
  this._filterUpToDate = false;
@@ -318,7 +303,7 @@ export class Node {
318
303
  this._isUnderCache = true;
319
304
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
320
305
  try {
321
- this.drawScene(cachedSceneCanvas, this, bufferCanvas);
306
+ this.drawScene(cachedSceneCanvas, this);
322
307
  }
323
308
  catch (e) {
324
309
  Util.releaseCanvas(cachedSceneCanvas._canvas);
@@ -329,8 +314,7 @@ export class Node {
329
314
  // descendants cached their opacity relative to this node while drawing
330
315
  this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY);
331
316
  sceneContext.restore();
332
- // the buffer is only needed while drawing
333
- Util.releaseCanvas(bufferCanvas._canvas);
317
+ cachedSceneCanvas._releaseIsolationCanvas();
334
318
  }
335
319
  // this will draw a red border around the cached box for
336
320
  // debugging purposes
@@ -441,28 +425,22 @@ export class Node {
441
425
  // redefine in Container and Shape
442
426
  throw new Error('abstract "getClientRect" method call');
443
427
  }
444
- _transformedRect(rect, top) {
445
- const points = [
446
- { x: rect.x, y: rect.y },
447
- { x: rect.x + rect.width, y: rect.y },
448
- { x: rect.x + rect.width, y: rect.y + rect.height },
449
- { x: rect.x, y: rect.y + rect.height },
450
- ];
451
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
452
- const trans = this.getAbsoluteTransform(top);
453
- points.forEach(function (point) {
454
- const transformed = trans.point(point);
455
- minX = Math.min(minX, transformed.x);
456
- minY = Math.min(minY, transformed.y);
457
- maxX = Math.max(maxX, transformed.x);
458
- maxY = Math.max(maxY, transformed.y);
459
- });
460
- return {
461
- x: minX,
462
- y: minY,
463
- width: maxX - minX,
464
- height: maxY - minY,
428
+ _getCachedSceneRect(config) {
429
+ const cache = config._forDrawing && !this._isUnderCache && this._getCanvasCache();
430
+ if (!cache)
431
+ return;
432
+ const rect = {
433
+ x: cache.x,
434
+ y: cache.y,
435
+ width: cache.scene.width / cache.scene.pixelRatio,
436
+ height: cache.scene.height / cache.scene.pixelRatio,
465
437
  };
438
+ return config.skipTransform
439
+ ? rect
440
+ : this._transformedRect(rect, config.relativeTo);
441
+ }
442
+ _transformedRect(rect, top) {
443
+ return this.getAbsoluteTransform(top)._getTransformedRect(rect);
466
444
  }
467
445
  _drawCachedSceneCanvas(context) {
468
446
  context.save();
@@ -1321,6 +1299,10 @@ export class Node {
1321
1299
  };
1322
1300
  for (key in attrs) {
1323
1301
  val = attrs[key];
1302
+ // JSON has no typed arrays, so typed line points are written as an array
1303
+ if (val instanceof TypedArray) {
1304
+ val = Array.from(val);
1305
+ }
1324
1306
  // if value is object and object is not plain
1325
1307
  // like class instance, we should skip it and to not include
1326
1308
  nonPlainObject =
@@ -1721,7 +1703,6 @@ export class Node {
1721
1703
  (stage ? stage.height() : 0),
1722
1704
  pixelRatio: pixelRatio,
1723
1705
  }), context = canvas.getContext();
1724
- const bufferCanvas = createBufferCanvas(canvas, x, y);
1725
1706
  if (config.imageSmoothingEnabled === false) {
1726
1707
  context._context.imageSmoothingEnabled = false;
1727
1708
  }
@@ -1729,10 +1710,9 @@ export class Node {
1729
1710
  if (x || y) {
1730
1711
  context.translate(-1 * x, -1 * y);
1731
1712
  }
1732
- this.drawScene(canvas, undefined, bufferCanvas);
1713
+ this.drawScene(canvas);
1733
1714
  context.restore();
1734
- // the buffer is only needed while drawing
1735
- Util.releaseCanvas(bufferCanvas._canvas);
1715
+ canvas._releaseIsolationCanvas();
1736
1716
  return canvas;
1737
1717
  }
1738
1718
  /**
@@ -2031,7 +2011,34 @@ export class Node {
2031
2011
  }
2032
2012
  return this;
2033
2013
  }
2014
+ _addSubtreeObserver(observer) {
2015
+ var _a;
2016
+ ((_a = this._subtreeObservers) !== null && _a !== void 0 ? _a : (this._subtreeObservers = new Set())).add(observer);
2017
+ Node._subtreeObserverCount++;
2018
+ }
2019
+ _removeSubtreeObserver(observer) {
2020
+ var _a;
2021
+ if ((_a = this._subtreeObservers) === null || _a === void 0 ? void 0 : _a.delete(observer)) {
2022
+ Node._subtreeObserverCount--;
2023
+ }
2024
+ }
2025
+ // Tells the observers of this node and of its ancestors that something below
2026
+ // them changed. A node's own changes reach its observers through its change
2027
+ // events, so a draw request starts at the parent. A container calls this
2028
+ // itself when its child list changes.
2029
+ _notifySubtreeChange() {
2030
+ if (!Node._subtreeObserverCount)
2031
+ return;
2032
+ for (let node = this; node; node = node.parent) {
2033
+ const observers = node._subtreeObservers;
2034
+ if (observers)
2035
+ for (const o of observers)
2036
+ o._onSubtreeChange(node);
2037
+ }
2038
+ }
2034
2039
  _requestDraw() {
2040
+ var _a;
2041
+ (_a = this.parent) === null || _a === void 0 ? void 0 : _a._notifySubtreeChange();
2035
2042
  if (Konva.autoDrawEnabled) {
2036
2043
  const drawNode = this.getLayer() || this.getStage();
2037
2044
  drawNode === null || drawNode === void 0 ? void 0 : drawNode.batchDraw();
@@ -2403,6 +2410,8 @@ export class Node {
2403
2410
  return no;
2404
2411
  }
2405
2412
  }
2413
+ // Number of registered observers. The ancestor walk is skipped while it is 0.
2414
+ Node._subtreeObserverCount = 0;
2406
2415
  // Perf: lets a listener inside an absoluteTransform cascade (e.g. Konva
2407
2416
  // .Transformer reacting to a stage drag fan-out across N attached nodes)
2408
2417
  // defer work until the cascade ends — collapses O(N) listener-driven calls
package/lib/Shape.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { GetClientRectConfig, NodeConfig } from './Node.ts';
2
2
  import { Node } from './Node.ts';
3
3
  import type { Context } from './Context.ts';
4
- import type { GetSet, Vector2d } from './types.ts';
4
+ import type { GetSet, Vector2d, IRect } from './types.ts';
5
5
  import type { HitCanvas, SceneCanvas } from './Canvas.ts';
6
6
  export type ShapeConfigHandler<TTarget> = {
7
7
  bivarianceHack(ctx: Context, shape: TTarget): void;
@@ -59,6 +59,7 @@ export type ShapeConfig = NodeConfig & {
59
59
  miterLimit?: number;
60
60
  sceneFunc?: (con: Context, shape: Shape) => void;
61
61
  hitFunc?: (con: Context, shape: Shape) => void;
62
+ selfRectFunc?: (shape: Shape) => IRect;
62
63
  shadowColor?: string;
63
64
  shadowBlur?: number;
64
65
  shadowOffset?: Vector2d;
@@ -169,7 +170,7 @@ export declare class Shape<Config extends ShapeConfig = ShapeConfig> extends Nod
169
170
  */
170
171
  intersects(point: Vector2d): boolean;
171
172
  destroy(): this;
172
- _useBufferCanvas(forceFill?: boolean): boolean;
173
+ _useBufferCanvas(forceFill?: boolean, opacity?: any): boolean;
173
174
  setStrokeHitEnabled(val: number): void;
174
175
  getStrokeHitEnabled(): boolean;
175
176
  /**
@@ -184,19 +185,11 @@ export declare class Shape<Config extends ShapeConfig = ShapeConfig> extends Nod
184
185
  * circle.getSelfRect(); // return {x: - circle.width() / 2, y: - circle.height() / 2, width:circle.width(), height:circle.height()}
185
186
  *
186
187
  */
187
- getSelfRect(): {
188
- x: number;
189
- y: number;
190
- width: number;
191
- height: number;
192
- };
193
- getClientRect(config?: ShapeGetClientRectConfig): {
194
- x: number;
195
- y: number;
196
- width: number;
197
- height: number;
198
- };
199
- drawScene(can?: SceneCanvas, top?: Node, bufferCanvas?: SceneCanvas): this;
188
+ getSelfRect(): IRect;
189
+ _getSelfRectForDrawing(): IRect;
190
+ getClientRect(config?: ShapeGetClientRectConfig): IRect;
191
+ _getStrokePadding(miterLimit?: number): number;
192
+ drawScene(can?: SceneCanvas, top?: Node): this;
200
193
  drawHit(can?: HitCanvas, top?: Node): this;
201
194
  /**
202
195
  * draw hit graph using the cached scene canvas
@@ -255,6 +248,7 @@ export declare class Shape<Config extends ShapeConfig = ShapeConfig> extends Nod
255
248
  miterLimit: GetSet<number, this>;
256
249
  perfectDrawEnabled: GetSet<boolean, this>;
257
250
  sceneFunc: GetSet<ShapeConfigHandler<this>, this>;
251
+ selfRectFunc: GetSet<((shape: Shape) => IRect) | undefined, this>;
258
252
  shadowColor: GetSet<string, this>;
259
253
  shadowEnabled: GetSet<boolean, this>;
260
254
  shadowForStrokeEnabled: GetSet<boolean, this>;
package/lib/Shape.js CHANGED
@@ -3,7 +3,7 @@ import { Transform, Util } from "./Util.js";
3
3
  import { Factory } from "./Factory.js";
4
4
  import { Node } from "./Node.js";
5
5
  import { getNumberValidator, getNumberOrAutoValidator, getStringValidator, getBooleanValidator, getStringOrGradientValidator, } from "./Validators.js";
6
- import { _registerNode } from "./Global.js";
6
+ import { _boundedShapes, _registerNode } from "./Global.js";
7
7
  import * as PointerEvents from "./PointerEvents.js";
8
8
  const HAS_SHADOW = 'hasShadow';
9
9
  const HAS_FILL = 'hasFill';
@@ -279,7 +279,9 @@ export class Shape extends Node {
279
279
  if (!stage) {
280
280
  return false;
281
281
  }
282
- const bufferHitCanvas = stage._syncBufferSize(stage.bufferHitCanvas);
282
+ const bufferHitCanvas = stage.bufferHitCanvas;
283
+ // lazy: allocated at stage size on first use
284
+ bufferHitCanvas.setSizeIfChanged(stage.width(), stage.height());
283
285
  bufferHitCanvas.getContext().clear();
284
286
  this.drawHit(bufferHitCanvas);
285
287
  const p = bufferHitCanvas.context.getImageData(Math.floor(point.x), Math.floor(point.y), 1, 1).data;
@@ -294,7 +296,7 @@ export class Shape extends Node {
294
296
  // why do we need buffer canvas?
295
297
  // it give better result when a shape has
296
298
  // stroke with fill and with some opacity
297
- _useBufferCanvas(forceFill) {
299
+ _useBufferCanvas(forceFill, opacity = this.getAbsoluteOpacity()) {
298
300
  // image and sprite still has "fill" as image
299
301
  // so they use that method with forced fill
300
302
  // it probably will be simpler, then copy/paste the code
@@ -306,7 +308,7 @@ export class Shape extends Node {
306
308
  }
307
309
  const hasFill = forceFill || this.hasFill();
308
310
  const hasStroke = this.hasStroke();
309
- const isTransparent = !this._isUnderCache && this.getAbsoluteOpacity() !== 1;
311
+ const isTransparent = !this._isUnderCache && opacity !== 1;
310
312
  if (hasFill && hasStroke && isTransparent) {
311
313
  return true;
312
314
  }
@@ -347,6 +349,9 @@ export class Shape extends Node {
347
349
  *
348
350
  */
349
351
  getSelfRect() {
352
+ const selfRectFunc = this.attrs.selfRectFunc;
353
+ if (selfRectFunc)
354
+ return { ...selfRectFunc.call(this, this) };
350
355
  const size = this.size();
351
356
  return {
352
357
  x: this._centroid ? -size.width / 2 : 0,
@@ -355,16 +360,34 @@ export class Shape extends Node {
355
360
  height: size.height,
356
361
  };
357
362
  }
363
+ _getSelfRectForDrawing() {
364
+ return this.getSelfRect();
365
+ }
358
366
  getClientRect(config = {}) {
367
+ const cachedRect = this._getCachedSceneRect(config);
368
+ if (cachedRect)
369
+ return cachedRect;
359
370
  const skipTransform = config.skipTransform;
360
371
  const relativeTo = config.relativeTo;
361
- const fillRect = this.getSelfRect();
372
+ const forDrawing = config._forDrawing;
373
+ // Painted bounds are measured in the canvas that draws the shape
374
+ // (relativeTo): non-scaling strokes and shadows use that canvas's axes.
375
+ // The identity transform normalizes negative sizes.
376
+ const fillRect = !forDrawing
377
+ ? this.getSelfRect()
378
+ : this.strokeScaleEnabled()
379
+ ? new Transform()._getTransformedRect(this._getSelfRectForDrawing())
380
+ : this._transformedRect(this._getSelfRectForDrawing(), relativeTo);
362
381
  const applyStroke = !config.skipStroke && this.hasStroke();
363
- const strokeWidth = (applyStroke && this.strokeWidth()) || 0;
382
+ const strokeWidth = applyStroke
383
+ ? forDrawing
384
+ ? this._getStrokePadding() * 2
385
+ : this.strokeWidth()
386
+ : 0;
364
387
  let strokeWidthX = strokeWidth;
365
388
  let strokeWidthY = strokeWidth;
366
389
  let collapsedStroke;
367
- if (strokeWidth && !this.strokeScaleEnabled()) {
390
+ if (!forDrawing && strokeWidth && !this.strokeScaleEnabled()) {
368
391
  // Strokes are constant in the canvas they are drawn into. A cached
369
392
  // ancestor supplies that coordinate space until its bitmap is rebuilt.
370
393
  let top = this;
@@ -395,26 +418,29 @@ export class Shape extends Node {
395
418
  }
396
419
  }
397
420
  }
398
- const fillAndStrokeWidth = fillRect.width + strokeWidthX;
399
- const fillAndStrokeHeight = fillRect.height + strokeWidthY;
400
- const applyShadow = !config.skipShadow && this.hasShadow();
401
- const shadowOffsetX = applyShadow ? this.shadowOffsetX() : 0;
402
- const shadowOffsetY = applyShadow ? this.shadowOffsetY() : 0;
403
- const preWidth = fillAndStrokeWidth + Math.abs(shadowOffsetX);
404
- const preHeight = fillAndStrokeHeight + Math.abs(shadowOffsetY);
405
- const blurRadius = (applyShadow && this.shadowBlur()) || 0;
406
- const width = preWidth + blurRadius * 2;
407
- const height = preHeight + blurRadius * 2;
408
- const rect = {
409
- width: width,
410
- height: height,
411
- x: -(strokeWidthX / 2 + blurRadius) +
412
- Math.min(shadowOffsetX, 0) +
413
- fillRect.x,
414
- y: -(strokeWidthY / 2 + blurRadius) +
415
- Math.min(shadowOffsetY, 0) +
416
- fillRect.y,
421
+ let rect = {
422
+ x: fillRect.x - strokeWidthX / 2,
423
+ y: fillRect.y - strokeWidthY / 2,
424
+ width: fillRect.width + strokeWidthX,
425
+ height: fillRect.height + strokeWidthY,
417
426
  };
427
+ if (forDrawing && this.strokeScaleEnabled()) {
428
+ rect = this._transformedRect(rect, relativeTo);
429
+ }
430
+ if (!config.skipShadow && this.hasShadow()) {
431
+ const scale = forDrawing ? this.getAbsoluteScale() : { x: 1, y: 1 };
432
+ const dx = this.shadowOffsetX() * scale.x;
433
+ const dy = this.shadowOffsetY() * scale.y;
434
+ const blur = this.shadowBlur() *
435
+ (forDrawing ? 2 * Math.min(Math.abs(scale.x), Math.abs(scale.y)) : 1);
436
+ rect.x += Math.min(0, dx) - blur;
437
+ rect.y += Math.min(0, dy) - blur;
438
+ rect.width += Math.abs(dx) + blur * 2;
439
+ rect.height += Math.abs(dy) + blur * 2;
440
+ }
441
+ if (forDrawing) {
442
+ return rect;
443
+ }
418
444
  if (!skipTransform) {
419
445
  const transformed = this._transformedRect(rect, relativeTo);
420
446
  if (collapsedStroke) {
@@ -430,14 +456,20 @@ export class Shape extends Node {
430
456
  }
431
457
  return rect;
432
458
  }
433
- drawScene(can, top, bufferCanvas) {
459
+ _getStrokePadding(miterLimit = this.miterLimit() || 10) {
460
+ // Custom paths can have sharper joins than the built-in geometry.
461
+ if (this.attrs.sceneFunc)
462
+ miterLimit = this.miterLimit() || 10;
463
+ return ((Math.abs(this.strokeWidth()) / 2) *
464
+ Math.max(this.lineCap() === 'square' ? Math.SQRT2 : 1, (this.lineJoin() || 'miter') === 'miter' ? miterLimit : 1));
465
+ }
466
+ drawScene(can, top) {
434
467
  // basically there are 3 drawing modes
435
468
  // 1 - simple drawing when nothing is cached.
436
469
  // 2 - when we are caching current
437
470
  // 3 - when node is cached and we need to draw it into layer
438
471
  const layer = this.getLayer();
439
472
  const canvas = can || layer.getCanvas(), context = canvas.getContext(), cachedCanvas = this._getCanvasCache(), drawFunc = this.getSceneFunc(), hasShadow = this.hasShadow();
440
- let stage;
441
473
  const cachingSelf = top === this;
442
474
  if (!(top ? this._isVisible(top) : this.isVisible()) && !cachingSelf) {
443
475
  return this;
@@ -455,66 +487,72 @@ export class Shape extends Node {
455
487
  return this;
456
488
  }
457
489
  context.save();
458
- // if buffer canvas is needed
459
- if (this._useBufferCanvas()) {
460
- stage = this.getStage();
461
- const bc = bufferCanvas || stage._syncBufferSize(stage.bufferCanvas);
462
- const bufferContext = bc.getContext();
463
- if (!bufferCanvas) {
464
- bufferContext.clear();
465
- }
466
- else if (!bc.width) {
467
- // cache() and toCanvas() hand over an empty buffer: size it to the
468
- // destination on first use and shift it to the buffer origin
469
- bc.setSize(canvas._logicalWidth, canvas._logicalHeight);
470
- bufferContext.translate(-bc.x, -bc.y);
471
- }
472
- else {
473
- // the buffer is translated, so reset the transform before clearing
490
+ try {
491
+ // if buffer canvas is needed; an empty canvas has nothing to draw into
492
+ if (canvas.width &&
493
+ canvas.height &&
494
+ this._useBufferCanvas(undefined, context._getOpacity(this))) {
495
+ // Built-in shapes, custom shapes with a selfRectFunc and isolated
496
+ // groups use a buffer the size of the painted bounds. Other custom
497
+ // drawing (sceneFunc, charRenderFunc, own classes) gets the whole
498
+ // canvas, since it can paint outside its bounds. The shadow is
499
+ // applied when the buffer is drawn, not inside it.
500
+ const bounded = !!context._opacityRoot ||
501
+ (!!this.attrs.selfRectFunc &&
502
+ this.getSelfRect === Shape.prototype.getSelfRect) ||
503
+ (!this.attrs.sceneFunc &&
504
+ !this.attrs.charRenderFunc &&
505
+ _boundedShapes.has(this.constructor));
506
+ const bc = canvas._prepareIsolationCanvas(bounded
507
+ ? this.getClientRect({
508
+ _forDrawing: true,
509
+ relativeTo: top,
510
+ skipShadow: true,
511
+ })
512
+ : undefined);
513
+ const bufferContext = bc.getContext();
474
514
  bufferContext.save();
475
- bufferContext.setTransform(1, 0, 0, 1, 0, 0);
476
- bufferContext.clearRect(0, 0, bc.width, bc.height);
515
+ bufferContext._applyLineJoin(this);
516
+ bufferContext._applyMiterLimit(this);
517
+ // layer might be undefined if we are using cache before adding to layer
518
+ const o = this.getAbsoluteTransform(top).getMatrix();
519
+ bufferContext.transform(o[0], o[1], o[2], o[3], o[4], o[5]);
520
+ drawFunc.call(this, bufferContext, this);
477
521
  bufferContext.restore();
522
+ if (hasShadow) {
523
+ context._applyShadow(this);
524
+ }
525
+ // if we are caching self, we don't need to apply opacity and global composite operation
526
+ // because it will be applied in the cache
527
+ if (!cachingSelf) {
528
+ context._applyOpacity(this);
529
+ context._applyGlobalCompositeOperation(this);
530
+ }
531
+ context._drawDeviceBuffer(bc);
478
532
  }
479
- bufferContext.save();
480
- // the buffer canvas is a separate context that does not inherit the
481
- // destination `imageSmoothingEnabled` flag, so propagate it to keep
482
- // pattern/image smoothing consistent with the target context.
483
- bufferContext.imageSmoothingEnabled = context.imageSmoothingEnabled;
484
- bufferContext._applyLineJoin(this);
485
- bufferContext._applyMiterLimit(this);
486
- // layer might be undefined if we are using cache before adding to layer
487
- const o = this.getAbsoluteTransform(top).getMatrix();
488
- bufferContext.transform(o[0], o[1], o[2], o[3], o[4], o[5]);
489
- drawFunc.call(this, bufferContext, this);
490
- bufferContext.restore();
491
- const ratio = bc.pixelRatio;
492
- if (hasShadow) {
493
- context._applyShadow(this);
494
- }
495
- // if we are caching self, we don't need to apply opacity and global composite operation
496
- // because it will be applied in the cache
497
- if (!cachingSelf) {
498
- context._applyOpacity(this);
499
- context._applyGlobalCompositeOperation(this);
533
+ else {
534
+ context._applyLineJoin(this);
535
+ context._applyMiterLimit(this);
536
+ if (!cachingSelf) {
537
+ const o = this.getAbsoluteTransform(top).getMatrix();
538
+ context.transform(o[0], o[1], o[2], o[3], o[4], o[5]);
539
+ context._applyOpacity(this);
540
+ context._applyGlobalCompositeOperation(this);
541
+ }
542
+ if (hasShadow) {
543
+ context._applyShadow(this);
544
+ }
545
+ drawFunc.call(this, context, this);
500
546
  }
501
- context.drawImage(bc._canvas, bc.x, bc.y, bc.width / ratio, bc.height / ratio);
502
547
  }
503
- else {
504
- context._applyLineJoin(this);
505
- context._applyMiterLimit(this);
506
- if (!cachingSelf) {
507
- const o = this.getAbsoluteTransform(top).getMatrix();
508
- context.transform(o[0], o[1], o[2], o[3], o[4], o[5]);
509
- context._applyOpacity(this);
510
- context._applyGlobalCompositeOperation(this);
511
- }
512
- if (hasShadow) {
513
- context._applyShadow(this);
514
- }
515
- drawFunc.call(this, context, this);
548
+ catch (error) {
549
+ // A throwing sceneFunc can leave a clip on the shared buffer.
550
+ canvas._releaseIsolationCanvas();
551
+ throw error;
552
+ }
553
+ finally {
554
+ context.restore();
516
555
  }
517
- context.restore();
518
556
  return this;
519
557
  }
520
558
  drawHit(can, top) {
@@ -544,8 +582,12 @@ export class Shape extends Node {
544
582
  const o = this.getAbsoluteTransform(top).getMatrix();
545
583
  context.transform(o[0], o[1], o[2], o[3], o[4], o[5]);
546
584
  }
547
- drawFunc.call(this, context, this);
548
- context.restore();
585
+ try {
586
+ drawFunc.call(this, context, this);
587
+ }
588
+ finally {
589
+ context.restore();
590
+ }
549
591
  return this;
550
592
  }
551
593
  /**
@@ -822,6 +864,24 @@ Factory.addGetterSetter(Shape, 'hitFunc');
822
864
  * context.fillStrokeShape(shape);
823
865
  * });
824
866
  */
867
+ Factory.addGetterSetter(Shape, 'selfRectFunc');
868
+ /**
869
+ * get/set the function that returns the self rectangle of a custom shape: the
870
+ * local, untransformed area its sceneFunc paints, before the stroke and shadow
871
+ * Konva adds. Use it when drawing goes outside the width and height box, so
872
+ * bounds, cache(), isolated groups and perfect drawing include that paint.
873
+ * Paint outside the returned rectangle can be clipped. Meant for custom
874
+ * shapes, and for Text drawn with charRenderFunc; built-in shapes that compute
875
+ * their own bounds may ignore it.
876
+ * @name Konva.Shape#selfRectFunc
877
+ * @method
878
+ * @param {Function} selfRectFunc function returning {x, y, width, height}
879
+ * @returns {Function}
880
+ * @example
881
+ * shape.selfRectFunc(() => ({ x: -10, y: -10, width: 120, height: 120 }));
882
+ * // back to the automatic width and height box
883
+ * shape.selfRectFunc(undefined);
884
+ */
825
885
  Factory.addGetterSetter(Shape, 'dash');
826
886
  /**
827
887
  * get/set dash array for stroke.
@@ -1177,7 +1237,7 @@ Factory.addGetterSetter(Shape, 'dashEnabled', true);
1177
1237
  */
1178
1238
  Factory.addGetterSetter(Shape, 'strokeScaleEnabled', true);
1179
1239
  /**
1180
- * get/set strokeScale enabled flag
1240
+ * get/set strokeScale enabled flag. Text and TextPath always scale their stroke.
1181
1241
  * @name Konva.Shape#strokeScaleEnabled
1182
1242
  * @method
1183
1243
  * @param {Boolean} enabled
package/lib/Stage.d.ts CHANGED
@@ -49,7 +49,6 @@ export declare class Stage extends Container<Layer, StageConfig> {
49
49
  _pointerEventType?: EventType;
50
50
  _pointerStates: Map<string, PointerState>;
51
51
  _lastClicks: Partial<Record<EventType, Click>>;
52
- bufferCanvas: SceneCanvas;
53
52
  bufferHitCanvas: HitCanvas;
54
53
  constructor(config: StageConfig);
55
54
  _validateAdd(child: any): void;
@@ -112,7 +111,6 @@ export declare class Stage extends Container<Layer, StageConfig> {
112
111
  */
113
112
  getIntersection(pos: Vector2d): Shape<import("./Shape.ts").ShapeConfig> | null;
114
113
  _resizeDOM(): void;
115
- _syncBufferSize<T extends SceneCanvas | HitCanvas>(canvas: T): T;
116
114
  add(layer: Layer, ...rest: any[]): this;
117
115
  getParent(): null;
118
116
  getLayer(): null;
package/lib/Stage.js CHANGED
@@ -234,7 +234,7 @@ export class Stage extends Container {
234
234
  if (index > -1) {
235
235
  stages.splice(index, 1);
236
236
  }
237
- Util.releaseCanvas(this.bufferCanvas._canvas, this.bufferHitCanvas._canvas);
237
+ Util.releaseCanvas(this.bufferHitCanvas._canvas);
238
238
  return this;
239
239
  }
240
240
  /**
@@ -339,13 +339,6 @@ export class Stage extends Container {
339
339
  layer.draw();
340
340
  });
341
341
  }
342
- // "perfect drawing" uses bufferCanvas, shape.intersects() uses
343
- // bufferHitCanvas; both are lazy - created at 0x0 and sized to the stage
344
- // on first use
345
- _syncBufferSize(canvas) {
346
- canvas.setSizeIfChanged(this.width(), this.height());
347
- return canvas;
348
- }
349
342
  add(layer, ...rest) {
350
343
  if (arguments.length > 1) {
351
344
  for (let i = 0; i < arguments.length; i++) {
@@ -921,12 +914,8 @@ export class Stage extends Container {
921
914
  };
922
915
  }
923
916
  _buildDOM() {
924
- // lazy buffer canvases, see _syncBufferSize
917
+ // lazy buffer canvas, sized by Shape.intersects() on first use
925
918
  // https://github.com/konvajs/konva/issues/2009
926
- this.bufferCanvas = new SceneCanvas({
927
- width: 0,
928
- height: 0,
929
- });
930
919
  this.bufferHitCanvas = new HitCanvas({
931
920
  pixelRatio: 1,
932
921
  width: 0,
package/lib/Util.d.ts CHANGED
@@ -35,6 +35,7 @@ export declare class Transform {
35
35
  x: number;
36
36
  y: number;
37
37
  };
38
+ _getTransformedRect(rect: IRect): IRect;
38
39
  /**
39
40
  * Apply translation
40
41
  * @method
package/lib/Util.js CHANGED
@@ -87,6 +87,31 @@ export class Transform {
87
87
  y: m[1] * point.x + m[3] * point.y + m[5],
88
88
  };
89
89
  }
90
+ // Axis-aligned bounds of a rectangle after this transform.
91
+ _getTransformedRect(rect) {
92
+ const [a, b, c, d, e, f] = this.m;
93
+ const x1 = rect.x, y1 = rect.y, x2 = rect.x + rect.width, y2 = rect.y + rect.height;
94
+ const xs = [
95
+ a * x1 + c * y1 + e,
96
+ a * x2 + c * y1 + e,
97
+ a * x2 + c * y2 + e,
98
+ a * x1 + c * y2 + e,
99
+ ];
100
+ const ys = [
101
+ b * x1 + d * y1 + f,
102
+ b * x2 + d * y1 + f,
103
+ b * x2 + d * y2 + f,
104
+ b * x1 + d * y2 + f,
105
+ ];
106
+ const minX = Math.min(xs[0], xs[1], xs[2], xs[3]);
107
+ const minY = Math.min(ys[0], ys[1], ys[2], ys[3]);
108
+ return {
109
+ x: minX,
110
+ y: minY,
111
+ width: Math.max(xs[0], xs[1], xs[2], xs[3]) - minX,
112
+ height: Math.max(ys[0], ys[1], ys[2], ys[3]) - minY,
113
+ };
114
+ }
90
115
  /**
91
116
  * Apply translation
92
117
  * @method